第4章 JUnit を使用した Eclipse Vert.x アプリケーションのテスト

getting-started プロジェクトで Eclipse Vert.x アプリケーションをビルドした後に、アプリケーションを JUnit 5 フレームワークでテストし、想定どおりに実行されるようにします。JUnit 5 のテストでは、Eclipse Vert.x pom.xml ファイルの次の 2 つの依存関係が使用されます。

<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, @BeforeEach, @DisplayName などのさまざまなアノテーションを提供します。Vertx および VertxTestContext インスタンスの非同期注入を要求するために使用されます。
  • 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

    テスト結果は、target/surefire-reports で確認できます。com.example.MyAppTest.txt ファイルにはテスト結果が含まれます。