Springbootテストcontroller getインタフェース

4327 ワード

package cn.edu.tju.se;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.core.JsonProcessingException;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TjuProjectApplication.class)
@WebAppConfiguration

public class test {
      
       
        MockMvc mvc;
        @Autowired  
        WebApplicationContext webApplicationConnect;  
  
        String expectedJson; 
        @Before  
        public void setUp() throws JsonProcessingException {  
            mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();  
      
        }  
       
        @Test
        public void show() throws Exception
        {
            String responseString = mvc.perform
                       (
                           get("/api/products")          // url, get
                          
                       )
                       .andExpect(status().isOk())    // 200
                       .andDo(print())         // 
                       .andReturn().getResponse().getContentAsString();   // 
                   System.out.println("----- json = " + responseString);
            
        
        }
       
        
}

 
転載先:https://www.cnblogs.com/LandingGuy/p/11371446.html