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

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());
    }

 

文章来自:http://www.cnblogs.com/fang9159/p/6106046.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3