第 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 等等,它们可用于请求对 VertxVertxTestContext 实例进行异步注入。
  • 运行时执行测试需要 junit-jupiter-engine 依赖项。

前提条件

  • 您已使用 pom.xml 文件构建了 Eclipse Vert.x getting-started 项目。

流程

  1. 打开生成的 pom.xml 文件并设置 Surefire Maven 插件的版本:

    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
    </plugin>
  2. 在根目录中创建目录结构 src/test/java/com/example/,然后导航到.

    $ mkdir -p src/test/java/com/example/
    $ cd src/test/java/com/example/
  3. 创建包含应用代码的 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));
      }
    }
  4. 使用 Maven 在我的应用上运行 JUnit 测试,可从应用的根目录运行以下命令:

    mvn clean verify

    您可以检查 目标/surefire-reports 的测试结果。com.example.MyAppTest.txt 文件包含测试结果。

Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.