application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
HelloController.java
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hello world!";
}
}
test工程
HelloControllerTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello world!")));
}
}
以上.
注.spring测试, 会去找有没有SpringBootconfiguration. 如果没有声明@SpringBootApplication
那么测试就不会成功.