服务端点需要将 url 返回到同一服务的另一个端点。 如何获取 Quarkus 服务运行的实际实时 http 端口?
当使用
quarkus dev
启动服务时,服务在 8080
上运行,
但当运行测试时,它会在 8081
上运行。
无论服务是否在测试中运行,quarkus.http.port
值始终为 8080
。
端点资源获取属性
quarkus.http.port
和 quarkus.http.host
配置属性注入以确定要返回的 url,但在运行 QuarkusTest 测试用例时,url 仍然包含 8080
而不是 8081
。
使用 ConfigProvider.getConfig()
而不是注入值没有什么区别。
因此测试用例无法根据收到的 url 执行下一个请求。
那么如何获取 Quarkus 启动时报告的实际 http 端口值?
更新:我没有通过将
添加到应用程序属性来解决此问题,但在我看来,Quarkus 应该在%test.quarkus.http.port=8081
中报告真实的 http 地址,无论哪个配置文件处于活动状态。quarkus.http.port
根据文档
虽然 Quarkus 默认情况下会监听端口
,但在运行测试时它默认为8080
。这允许您在并行运行应用程序的同时运行测试。8081
...
您可以通过在quarkus.http.test-port
中配置quarkus.http.test-ssl-port
(用于 HTTP)和application.properties
(用于 HTTPS)来配置测试使用的端口
要确定绑定的http端口,可以使用
io.vertx.core.http.HttpServerRequest
,例如:
@Path("/hello")
public class ExampleResource {
@Context
HttpServerRequest serverRequest;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getPort() {
var port = serverRequest.localAddress().port();
Log.infof("current port is: %s ", port);
return port;
}
}
但是,如果您想为端点创建 URL(例如带有 Location 标头的复杂 201-Created 响应),我建议使用
jakarta.ws.rs.core.UriBuilder
@Path("/hello")
public class ExampleResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/{id}")
public String get(@PathParam("id") String id) {
return "Got id: " + id;
}
@POST
public Response create() {
var uri = UriBuilder.
fromMethod(ExampleResource.class, "get")
.build("newId");
return Response.created(uri).build();
}
}
现在,这个测试用例将通过
@QuarkusTest
class ExampleResourceTest {
@Test
void testCreate() {
var loc = given()
.when().post("/hello")
.then()
.statusCode(201)
.extract().header("Location");
assertEquals(8081, URI.create(loc).getPort());
}
}