1. 概述
Spring 提供了許多功能,幫助我們測試代碼。有時我們需要使用特定的配置屬性,以便在測試用例中設置所需的場景。
在這些情況下,我們可以利用 <em>@TestPropertySource</em> 註解。使用此工具,我們可以定義優先級高於項目中使用任何其他來源的配置源。
因此,在本簡短教程中,我們將看到使用該註解的示例。此外,我們還將分析其默認行為和它支持的主要屬性。
要了解更多關於 Spring Boot 測試的信息,我們建議您查看我們的“Spring Boot 中的測試”教程。
2. 依賴項
將所有必需的庫包含在我們的項目中,最簡單的方法是將其添加至 spring-boot-starter-test 構件到我們的 pom.xml 文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>我們可以檢查 Maven Central 以驗證我們是否正在使用 Spring Boot Starter Test 的最新版本。該 starter 庫。
3. 如何使用 @TestPropertySource
假設我們通過使用 Spring 註解 @Value 注入屬性值:
@Component
public class ClassUsingProperty {
@Value("${baeldung.testpropertysource.one}")
private String propertyOne;
public String retrievePropertyOne() {
return propertyOne;
}
}我們隨後將使用 <em class="test-property-source">@TestPropertySource</em> 類級別註解來定義一個新的配置源,並覆蓋該屬性的值:
@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");
}
}通常,當我們使用此測試標註時,我們也會包含 @ContextConfiguration 以便加載和配置場景中的 ApplicationContext。
默認情況下,@TestPropertySource 標註會嘗試加載與聲明標註的類相關的 properties 文件。
例如,如果我們的測試類位於 com.baeldung.testpropertysource 包中,那麼我們需要將文件 com/baeldung/testpropertysource/DefaultTest.properties 放入我們的 classpath 中。
然後我們將它添加到我們的 resources 文件夾中:
# DefaultTest.properties
baeldung.testpropertysource.one=default-value此外,還可以更改默認的配置文件位置,或者添加優先級更高的額外屬性:
@TestPropertySource(locations = "/other-location.properties",
properties = "baeldung.testpropertysource.one=other-property-value")可以傳遞多個自定義屬性。可以通過使用數組字面量來實現:
@TestPropertySource(
locations = "/other-location.properties",
properties = """
baeldung.testpropertysource.one=one
baeldung.testpropertysource.two=two
""")
public class MultiplePropertiesInPropertySourceTextBlockIntegrationTest {
使用 Java 15 及更高版本,以及 Spring 6.1.0 或更高版本,我們有選擇使用多行文本塊的選項:
@TestPropertySource(
locations = "/other-location.properties",
properties = """
baeldung.testpropertysource.one=one
baeldung.testpropertysource.two=two
""")
public class MultiplePropertiesInPropertySourceTextBlockIntegrationTest {
最後,我們可以指定是否希望從父類繼承位置和屬性值。因此,我們可以切換inheritLocations和inheritProperties屬性,這些屬性默認設置為true。
4. 結論
通過這個簡單的示例,我們學習瞭如何有效地使用 Spring 註解 @TestPropertySource。