首页 > 编程语言 > 详细

Spring Boot 编写Mock测试

时间:2019-12-10 01:53:35      阅读:112      评论:0      收藏:0      [点我收藏+]

引入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 = []

 

Spring Boot 编写Mock测试

原文:https://www.cnblogs.com/fubinhnust/p/12013999.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!