@TestPropertySourceのクイックガイド

@TestPropertySourceのクイックガイド

 1. 概要

Springには、コードのテストに役立つ多くの機能が用意されています。 テストケースで目的のシナリオを設定するために、特定の構成プロパティを使用する必要がある場合があります。

これらの状況では、we can make use of the @TestPropertySource annotation. With this tool, we can define configuration sources that have higher precedence than any other source used in the project.

したがって、この短いチュートリアルでは、このアノテーションを使用する例を示します。 また、デフォルトの動作とサポートされる主な属性を分析します。

Spring Bootでのテストの詳細については、‘Testing in Spring Boot' tutorialを確認することをお勧めします。

2. 依存関係

プロジェクトに必要なすべてのライブラリを含める最も簡単な方法は、pom.xmlファイルにspring-boot-starter-testアーティファクトを追加することです。


    org.springframework.boot
    spring-boot-starter-test
    test
    2.0.5.RELEASE

Maven Centralをチェックして、最新バージョンのstarter libraryを使用していることを確認できます。

3. @TestPropertySourceの使用方法

@ValueのSpringアノテーションを使用してプロパティの値を挿入することにより、プロパティの値を使用していると想像してみてください。

@Component
public class ClassUsingProperty {

    @Value("${example.testpropertysource.one}")
    private String propertyOne;

    public String retrievePropertyOne() {
        return propertyOne;
    }
}

次に、@TestPropertySource classレベルのアノテーションを使用して、新しい構成ソースを定義し、そのプロパティの値をオーバーライドします。

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ClassUsingProperty.class)
@TestPropertySource
public class DefaultTest {

    @Autowired
    ClassUsingProperty classUsingProperty;

    @Test
    public void givenDefaultTPS_whenVariableRetrieved_thenDefaultFileReturned() {
        String output = classUsingProperty.retrievePropertyOne();

        assertThat(output).isEqualTo("default-value");
    }
}

通常、このテストアノテーションを使用する場合は常に、シナリオのApplicationContextをロードして構成するために、@ContextConfiguration oneも含めます。

デフォルトでは、@TestPropertySourceアノテーションは、アノテーションを宣言したクラスに関連するpropertiesファイルを読み込もうとします。

この場合、たとえば、テストクラスがcom.example.testpropertysourceパッケージにある場合、クラスパスにファイルcom/example/testpropertysource/DefaultTest.properties が必要になります。

次に、それをリソースフォルダに追加しましょう。

# DefaultTest.properties
example.testpropertysource.one=default-value

さらに、デフォルトの構成ファイルの場所を変更したり、さらに優先順位の高いプロパティを追加したりできます。

@TestPropertySource(locations = "/other-location.properties",
  properties = "example.testpropertysource.one=other-property-value")

最後に、スーパークラスからlocationspropertiesの値を継承するかどうかを指定できます。 したがって、デフォルトでtrueであるinheritLocations属性とinheritProperties 属性を切り替えることができます。

4. 結論

この簡単な例で、@TestPropertySourceSpringアノテーションを効果的に使用する方法を学びました。

さまざまなシナリオの例をour Github repositoryで見つけることができます。