gpt4 book ai didi

java - 如何在 Vert.x 中对 Handler 进行单元测试?

转载 作者:行者123 更新时间:2023-12-01 19:19:25 24 4
gpt4 key购买 nike

我有:

Router.router(vertx).route().handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
HttpServerRequest request = event.request();
Buffer body = event.getBody();
HttpServerResponse response = event.response();
// Some code to test
response.setStatusCode(200);
response.end();
}
});

如何通过提供准备好的请求和正文并检查响应来对此进行单元测试?

最佳答案

通常测试此类端点更多的是集成测试而不是单元测试。没必要 mock 一切。模拟旨在测试一些在您的测试上下文中不可用的外部服务。这是使用 vert.x 进行集成测试的示例:

@ExtendWith(VertxExtension.class)
class IntegrationTest {
private static RequestSpecification requestSpecification;

@BeforeAll
static void prepareSpec() {
requestSpecification = new RequestSpecBuilder()
.addFilters(asList(new ResponseLoggingFilter(), new RequestLoggingFilter()))
.setBaseUri("http://localhost:3002/")// Depends on your verticle config.
.build();
}

@BeforeEach
void setup(Vertx vertx, VertxTestContext testContext) {

vertx
.deployVerticle(new MyVerticle(),
ar -> {
if(ar.succeeded()) {
testContext.completeNow();
} else {
testContext.failNow(ar.cause());
}
}
);
}

@Test
@DisplayName("Test message")
void test() {
JsonObject body = new JsonObject();//Fill it as you want

given(requestSpecification)
.contentType(ContentType.JSON)
.body(body.encode())
.post("/yourreqest")//Your resource path
.then()
.assertThat()
.statusCode(200);//expected status
}

关于java - 如何在 Vert.x 中对 Handler<RoutingContext> 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59378705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com