码迷,mamicode.com
首页 > 编程语言 > 详细

使用MockMvc编写spring boot的controller的测试用例

时间:2016-11-27 11:38:47      阅读:1079      评论:0      收藏:0      [点我收藏+]

标签:set   开始   上下文   注解   with   color   ssr   script   blog   

springboot自带测试模块。

 

注解需要:

@SpringApplicationConfiguration(classes = ComputeServiceApplication.class)

这样就可以引入环境上下文。

完整注解如下:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ComputeServiceApplication.class)
@WebAppConfiguration

@Before

初始化MockMvc实例

public void setUp() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

 

@Test

开始写用例

需要初始化request的实例,例子如下。

@Test
    public void testComputeController() throws Exception {
        RequestBuilder request = null;
        request  = get("/userinfo/209799");
        mvc.perform(request).andExpect(status().isOk())
                .andExpect(content().string(
                        equalTo("{\"name\":\"fx\",\"description\":\"old man\",\"age\":\"50\"}")));

        request = get("/add?a=5&b=7");
        mvc.perform(request).andExpect(status().isOk())
                .andExpect(content().string(equalTo("12")));
        request = get("/test");
        mvc.perform(request).andExpect(status().isOk());
    }

 

使用MockMvc编写spring boot的controller的测试用例

标签:set   开始   上下文   注解   with   color   ssr   script   blog   

原文地址:http://www.cnblogs.com/fang9159/p/6106046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!