Spring 5 @EnabledIfアノテーションを使ったテスト

@EnabledIfアノテーションを使用したSpring 5のテスト

1. 前書き

この簡単な記事では、JUnit 5を使用してSpring 5の@EnabledIfおよび@DisabledIfアノテーションを発見します。

簡単に言えば、those annotations make it possible to disable/enable particular test if a specified condition is met.

簡単なテストクラスを使用して、これらのアノテーションがどのように機能するかを示します。

@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class)
public class Spring5EnabledAnnotationIntegrationTest {

    @Configuration
    static class Config {}
}

2. @EnabledIf

テキストリテラル“true”を使用したこの簡単なテストをクラスに追加しましょう。

@EnabledIf("true")
@Test
void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() {
    assertTrue(true);
}

このテストを実行すると、正常に実行されます。

ただし、提供されたString“false”に置き換えると、実行されません。

image

テストを静的に無効にする場合は、専用の@Disabledアノテーションがあることに注意してください。

3. プロパティプレースホルダーを含む@EnabledIf

@EnabledIfを使用するより実用的な方法は、プロパティプレースホルダーを使用することです。

@Test
@EnabledIf(
  expression = "${tests.enabled}",
  loadContext = true)
void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() {
    // ...
}

まず、Springコンテキストが読み込まれるように、loadContextパラメーターがtrueに設定されていることを確認する必要があります。

デフォルトでは、このパラメーターは、不要なコンテキストのロードを回避するためにfalseに設定されています。

4. SpEL式を使用した@EnabledIf

最後に、we can use the annotation with Spring Expression Language (SpEL) expressions.

たとえば、JDK 1.8を実行しているときにのみテストを有効にできます

@Test
@EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}")
void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() {
    assertTrue(true);
}

5. @DisabledIf

この注釈は@EnabledIf.の反対です

たとえば、Java 1.7で実行中のテストを無効にできます。

@Test
@DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}")
void givenDisabledIf_WhenTrue_ThenTestNotExecuted() {
    assertTrue(true);
}

6. 結論

この短い記事では、SpringExtensionを使用したJUnit 5テストでの@EnabledIfおよび@DisabledIfアノテーションの使用例をいくつか紹介しました。

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