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