如何使用RestAssured在Spring引导集成测试中为客户端调用设置端口



我正在努力为我的应用程序编写一个合适的集成测试。我使用了放心的和maven的故障保护插件。目前我有一个例外:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost/api/deactivate/1": Connect to localhost:80 [localhost/127.0.0.1] failed: Connection refused (Connection refused); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:80 [localhost/127.0.0.1] failed: Connection refused (Connection refused)

我的假设是url中缺少端口(8080(存在问题。但是我不知道为什么。我有两个模块,一个正在调用另一个。第一个运行在端口8081上,第二个运行在8080上。

这是模块1的测试配置(模块2的配置类似,只是另一个端口(。我的测试扩展了这个类别:

public abstract class AbstractDeactivationIT {
@BeforeAll
public static void configureRestAssured() {
RestAssured.port = Integer.parseInt(System.getProperty("it.deactivation.port", "8081"));
System.out.println("RestAssured: using port " + RestAssured.port);
// authentication config

...
var mapper = ObjectMapperFactory.defaultConfig().build();
RestAssured.config = RestAssured.config()
.logConfig(logConfig().enableLoggingOfRequestAndResponseIfValidationFails())
.objectMapperConfig(objectMapperConfig().jackson2ObjectMapperFactory((type, s) -> mapper));
}
}

我的测试:

@Test
void testDeactivation_forCorrectRequestData() {
// @formatter:off
given()
.contentType(JSON)
.body(DeactivationRequest.builder()
...
.build()
).
when()
.post("/api/deactivations").
then()
.statusCode(201);
// @formatter:on
}

在调试时,我注意到第一个调用是正确构建的(使用端口8081(,但客户端调用没有8080端口。我的application-local.yml文件中有两个带有端口的url。我也有类似的测试,但方向相反,所以模块2正在调用模块1,这很好,没有任何端口问题。Url构建正确。

RestAssured.port是一个静态字段。如果在相同的故障保护配置中运行两个测试,那么测试的顺序可能会与静态属性相混淆。

不要使用静态RestAssured配置,而是为每个RestAssured调用构造正确的带有端口的url。

您可以将get()post()等方法与url一起使用,而不是使用相对路径(例如:.when().get("http://myhost.org:80/doSomething");(。来源:https://github.com/rest-assured/rest-assured/wiki/Usage#default-值

在你的情况下,它可能是:

given()
.contentType(JSON)
.body(DeactivationRequest.builder()
...
.build()
).
when()
.post("http://localhost:8081/api/deactivations").
then()
.statusCode(201);

最新更新