JUnit5 @RunWith

JUnit5 @RunWith

1. 前書き

この簡単な記事では、JUnit 5フレームワークでの@RunWithアノテーションの使用法について説明します。

JUnit 5では、the @RunWith annotation has been replaced by the more powerful @ExtendWith annotation

ただし、下位互換性のために、@RunWithアノテーションをJUnit5で引き続き使用できます。

2. JUnit4ベースのランナーでテストを実行する

@RunWithアノテーションを使用して、他の古いJUnit環境でJUnit5テストを実行できます。

JUnit4のみをサポートするEclipseバージョンでこれらのテストを実行する例を見てみましょう。

まず、テストするクラスを作成しましょう。

public class Greetings {
    public static String sayHello() {
        return "Hello";
    }
}

次に、このプレーンなJUnit5テストを作成しましょう。

public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

最後に、このアノテーションを追加して、テストを実行できるようにします。

@RunWith(JUnitPlatform.class)
public class GreetingsTest {
    // ...
}

JUnitPlatformクラスはJUnit4ベースのランナーであり、JUnitプラットフォームでJUnit4テストを実行できます。

keep in mind that JUnit4 does not support all the features of the new JUnit Platform, so this runner has a limited functionality.しましょう

Eclipseでテストの結果を確認すると、JUnit4ランナーが使用されたことがわかります。

junit4 test

3. JUnit5環境でのテストの実行

JUnit5をサポートするEclipseバージョンで同じテストを実行してみましょう。 この場合、@RunWithアノテーションは不要になり、ランナーなしでテストを記述できます。

public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

テスト結果は、現在JUnit5ランナーを使用していることを示しています。

junit5 test

4. JUnit4ベースのランナーからの移行

次に、JUnit4ベースのランナーを使用するテストをJUnit5に移行しましょう。

例としてSpringテストを使用します。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

このテストをJUnit5に移行する場合は、@RunWithアノテーションを新しい@ExtendWithに置き換える必要があります。

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

SpringExtensionクラスはSpring 5によって提供され、Spring TestContextFrameworkをJUnit5に統合します。 @ExtendWithアノテーションは、Extensionインターフェースを実装するすべてのクラスを受け入れます。

5. 結論

この短い記事では、JUnit5フレームワークでのJUnit 4の@RunWithアノテーションの使用について説明しました。

例の完全なソースコードは、over on GitHubで入手できます。