SpringBoot之MockMvc

依赖


     org.springframework.boot
     spring-boot-starter-test
     test
 

Code

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@SpringBootTest
public class HelloTest {
    @Test
    public void hello(){
        System.out.println("hello world");
    }

    private MockMvc mockMvc;

    //前置条件,将需要测试的类new出来
    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(new WebController()).build();
    }
    

    //print可以打印出请求和响应相关信息,但必须主动引入上面那个print
    @Test
    public void getHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明")
                .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
    }
    
    //用来测试是否满足某些条件
    @Test
    public void getHello2() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明")
                .accept(MediaType.APPLICATION_JSON_UTF8))/*.andDo(print())*/
                .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("小明")));
    }
    
    //只输出打印的数据
    @Test
    public void getUser() throws Exception {
        String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/getUser"))
                .andReturn().getResponse().getContentAsString();
        System.out.println("result : "+responseString);
    }
    

    //带参数的测试
    @Test
    public void saveUsers() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/saveUser")
                .param("name","")
                .param("age","666")
                .param("pass","test")
        );
    }
}

转自CSND图文课-------作者:纯洁的微笑

你可能感兴趣的:(SpringBoot之MockMvc)