JUnit 5 @Testアノテーション

JUnit 5 @Testアノテーション

1. 概要

この記事では、JUnitの@Testアノテーションについて簡単に説明します。 この注釈は、単体テストおよび回帰テストを実行するための強力なツールを提供します。

2. Mavenの構成

latest version of JUnit 5を使用するには、次のMaven依存関係を追加する必要があります。


    org.junit.jupiter
    junit-jupiter-engine
    5.1.0
    test

Mavenにこの依存関係を最終ビルドに含めたくないため、testスコープを使用します。

surefireプラグインはまだネイティブでJUnit5を完全にサポートしていないため、we’ll also need to add a providerは、Mavenにテストの場所を指示します。


    maven-surefire-plugin
    2.19.1
    
        
            org.junit.platform
            junit-platform-surefire-provider
            1.0.2
        
    

この構成では、at the time of writing, version 2.20.x is not compatible with the junit-platform-surefire-providerであるため、surefire2.19.1を使用します。

3. テスト中のメソッド

まず、テストシナリオで使用して、@Testアノテーションの機能を紹介する簡単なメソッドを作成しましょう。

public boolean isNumberEven(Integer number) {
    return number % 2 == 0;
}

このメソッドは、渡された引数が偶数の場合はtrueを返し、それ以外の場合はfalseを返す必要があります。 それでは、想定どおりに機能するかどうかを確認しましょう。

4. メソッドのテスト

この例では、2つのシナリオを具体的に確認します。

  • 偶数が与えられた場合、メソッドはtrueを返す必要があります

  • 奇数が与えられた場合、メソッドはfalseを返す必要があります

これは、実装コードがさまざまなパラメーターを使用してisNumberEvenメソッドを呼び出し、結果が期待どおりであることを確認することを意味します。

In order for the tests to be recognized as such, we’ll add the @Test annotation.これらはクラスにいくつでも含めることができますが、関連するものだけをまとめることをお勧めします。 a test must not be private, nor may it return a valueにも注意してください。そうしないと、無視されます。

これらの考慮事項を考慮して、テストメソッドを記述しましょう。

@Test
void givenEvenNumber_whenCheckingIsNumberEven_thenTrue() {
    boolean result = bean.isNumberEven(8);

    Assertions.assertTrue(result);
}

@Test
void givenOddNumber_whenCheckingIsNumberEven_thenFalse() {
    boolean result = bean.isNumberEven(3);

    Assertions.assertFalse(result);
}

ここでMavenビルドを実行すると、the surefire plugin will go through all the annotated methods in the classes placed under src/test/java and execute them、テストの失敗が発生するとビルドが失敗します.

JUnit 4から来た場合、be aware that in this version the annotation doesn’t accept any parameters.タイムアウトまたはスローされた例外をチェックするために、代わりにアサーションを使用します。

@Test
void givenLowerThanTenNumber_whenCheckingIsNumberEven_thenResultUnderTenMillis() {
    Assertions.assertTimeout(Duration.ofMillis(10), () -> bean.isNumberEven(3));
}

@Test
void givenNull_whenCheckingIsNumberEven_thenNullPointerException() {
    Assertions.assertThrows(NullPointerException.class, () -> bean.isNumberEven(null));
}

5. 結論

このクイックチュートリアルでは、@Testアノテーションを使用して簡単なJUnitテストを実装および実行する方法を示しました。

JUnitフレームワークの詳細については、一般的な紹介を提供するthis postを参照してください。

例で使用されているすべてのコードは、GitHub projectで使用できます。