我被赋予了在java Controller中创建基本端点的任务。我想出了以下内容。
@RestController
public class SimpleController{
@RequestMapping("/info")
public String displayInfo() {
return "This is a Java Controller";
}
@RequestMapping("/")
public String home(){
return "Welcome!";
}
}
令人讨厌的是,它是如此简单,但我想不出如何创建一个ControllerTest,我只需要测试代码。这一切都在工作和手动测试。有帮助吗?谢谢
对于通过http的完整系统集成测试,您可以使用TestRestTemplate:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Welcome!");
}
}
对于没有实际启动Web服务器的较轻的测试,您可以使用Spring MockMVC:https://spring.io/guides/gs/testing-web/
@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}