JUnit 5で、すべてのテストの前にコードを実行する方法 質問する

JUnit 5で、すべてのテストの前にコードを実行する方法 質問する

アノテーション@BeforeAllは、すべてのテストの前に実行されるメソッドをマークします。クラス

http://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

しかし、事前にコードを実行する方法はあるのでしょうか?全てすべてのクラスでテストを実施しますか?

テストでは特定のデータベース接続セットが使用され、これらの接続のグローバルなワンタイムセットアップが実行されるようにしたい。前にランニングどれでもテスト。

ベストアンサー1

これは、カスタム拡張機能を作成することで JUnit5 で可能になり、そこからルート テスト コンテキストにシャットダウン フックを登録できるようになりました。

拡張機能は次のようになります。

import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.GLOBAL;

public class YourExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

    private static boolean started = false;

    @Override
    public void beforeAll(ExtensionContext context) {
        if (!started) {
            started = true;
            // Your "before all tests" startup logic goes here
            // The following line registers a callback hook when the root test context is shut down
            context.getRoot().getStore(GLOBAL).put("any unique name", this);
        }
    }

    @Override
    public void close() {
        // Your "after all tests" logic goes here
    }
}

次に、これを少なくとも 1 回実行する必要があるテスト クラスに、次のように注釈を付けることができます。

@ExtendWith({YourExtension.class})

この拡張機能を複数のクラスで使用すると、起動およびシャットダウン ロジックは 1 回だけ呼び出されます。

おすすめ記事