使用 Spring Boot 运行集成测试

x33g5p2x  于2022-09-28 转载在 Spring  
字(1.5k)|赞(0)|评价(0)|浏览(646)

一个常见的问题是,如果您想在构建应用程序的同一阶段在 Spring Boot 应用程序中运行集成测试,您将无法将测试连接到应用程序:

$ mvn install spring-boot:run  [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.434 s <<< FAILURE! - in com.example.testrest.DemoApplicationTests [ERROR] testCustomerList(com.example.testrest.DemoApplicationTests)  Time elapsed: 1.004 s  <<< ERROR! java.net.ConnectException: Connection refused (Connection refused)

这是因为在测试阶段选择的端口是随机的,因此大多数时候您会收到连接被拒绝的异常。

如何修复它

在旧版本的 Spring Boot 中,您可以将注释 @IntegrationTest 添加到您的应用程序以解决该问题,但是在 Spring Boot 2 中已弃用并删除了该注释。解决此问题的最简单方法是指定 SpringBootTest。 @SpringBootTest 类中的 WebEnvironment.DEFINED_PORT 如下:

package com.example.testrest;

import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static io.restassured.RestAssured.get;
import static org.hamcrest.CoreMatchers.is;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {
  @Test
  public void testCustomerList() {
    get("http://localhost:8080/list").then().assertThat().statusCode(200).body("size()", is(5));
    get("http://localhost:8080/one/0")
        .then()
        .assertThat()
        .statusCode(200)
        .body("name", Matchers.equalTo("Fred"));
    get("http://localhost:8080/one/1")
        .then()
        .assertThat()
        .statusCode(200)
        .body("name", Matchers.equalTo("Barney"));
  }
}

相关文章

微信公众号

最新文章

更多