Spring Boot 编写Mock测试

杀马特。学长 韩版系。学妹 提交于 2019-12-09 23:48:53

引入Maven依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

测试Controller的代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setupMockMvc(){
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

     @Test
    public void testTes() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/api/test") // 发出请求
                .contentType(MediaType.APPLICATION_JSON_UTF8) //期望的内容类型
                .accept(MediaType.APPLICATION_JSON_UTF8)) //期望接收的内容类型
                .andExpect(MockMvcResultMatchers.status().isOk()) //期望结果是200
                .andDo(MockMvcResultHandlers.print()); // 期望把结果打印出来
     }
}

 

Mock测试打印输出的日志:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/test
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json;charset=UTF-8"]
             Body = null
    Session Attrs = {}

Handler:
             Type = com.fubin.controller.TestController
           Method = public java.lang.Object com.fubin.controller.TestController.test()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json;charset=UTF-8"]
     Content type = application/json;charset=UTF-8
             Body = {"id":2,"name":"fubin","age":28,"url":"https://fubin.org.cn"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!