多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 控制器 ~~~ package com.like.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("index") public String index() { return "hello world"; } } ~~~ ## 测试 ~~~ package com.like.controller; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(SpringRunner.class) //指定SpringRunner来运行测试 @SpringBootTest public class test { private MockMvc mvc; @Before public void setUp() { mvc = MockMvcBuilders.standaloneSetup(new TestController()).build(); } @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/index").accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultHandlers.print()) //使用MockMvcResultHandlers.print()来打印响应信息 .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("hello world"))); } } ~~~