Spring (55)Spring Boot的测试支持
    		       		warning:
    		            这篇文章距离上次修改已过416天,其中的内容可能已经有所变动。
    		        
        		                
                Spring Boot提供了一套完整的测试支持,包括Spring Test & Spring Boot Test模块,以便开发者能够编写单元测试和集成测试。
以下是一个使用Spring Boot Test进行集成测试的简单示例:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerIntegrationTest {
 
    @Autowired
    private TestRestTemplate restTemplate;
 
    @LocalServerPort
    private int port;
 
    @Test
    public void givenGetRequestToRoot_whenHomePage_thenCorrectResponse() {
        ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/", String.class);
 
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).contains("Home Page");
    }
}在这个例子中,@SpringBootTest注解用于启动Spring上下文和加载应用程序的配置。@LocalServerPort注解用于注入随机生成的端口号,以便测试可以正确地连接到正在运行的服务器。TestRestTemplate提供了一种方便的方式来发送HTTP请求并接收响应。
这个测试类使用了@RunWith(SpringRunner.class)来运行测试,这是Spring框架中用于集成测试的运行器。这个测试方法givenGetRequestToRoot_whenHomePage_thenCorrectResponse()发送一个GET请求到应用程序的根路径并断言返回的HTTP状态码是200(OK)以及响应体包含"Home Page"字样。
评论已关闭