第 4 章 使用 JUnit 测试 Eclipse Vert.x 应用程序
在 getting-started 项目中构建了 Eclipse Vert.x 应用后,使用 JUnit 5 框架测试您的应用程序以确保它按预期运行。Eclipse Vert.x pom.xml 文件中的以下两个依赖项用于 JUnit 5 测试:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>-
测试需要
vertx-junit5依赖项。JUnit 5 提供了各种注释,如@Test、@Before 每个、@DisplayName等等,它们可用于请求对Vertx和VertxTestContext实例进行异步注入。 -
运行时执行测试需要
junit-jupiter-engine依赖项。
前提条件
-
您已使用
pom.xml文件构建了 Eclipse Vert.xgetting-started项目。
流程
打开生成的
pom.xml文件并设置 Surefire Maven 插件的版本:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> </plugin>在根目录中创建目录结构
src/test/java/com/example/,然后导航到.$ mkdir -p src/test/java/com/example/ $ cd src/test/java/com/example/
创建包含应用代码的 Java 类文件
MyTestApp.java。package com.example; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.vertx.core.Vertx; import io.vertx.core.http.HttpMethod; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; @ExtendWith(VertxExtension.class) class MyAppTest { @BeforeEach void prepare(Vertx vertx, VertxTestContext testContext) { // Deploy the verticle vertx.deployVerticle(new MyApp()) .onSuccess(ok -> testContext.completeNow()) .onFailure(failure -> testContext.failNow(failure)); } @Test @DisplayName("Smoke test: check that the HTTP server responds") void smokeTest(Vertx vertx, VertxTestContext testContext) { // Issue an HTTP request vertx.createHttpClient() .request(HttpMethod.GET, 8080, "127.0.0.1", "/") .compose(request -> request.send()) .compose(response -> response.body()) .onSuccess(body -> testContext.verify(() -> { // Check the response assertEquals("Greetings!", body.toString()); testContext.completeNow(); })) .onFailure(failure -> testContext.failNow(failure)); } }使用 Maven 在我的应用上运行 JUnit 测试,可从应用的根目录运行以下命令:
mvn clean verify
您可以检查
目标/surefire-reports的测试结果。com.example.MyAppTest.txt文件包含测试结果。