[英]@TestPropertySource annotations on test class and meta annotation not merged
在Spring Boot中直接在測試類上以及在元注釋上同時使用@TestPropertySource
,兩個屬性源的屬性不會合並,而是僅顯示在測試類上定義的屬性。
JUnit 5測試:
@CustomTest
@TestPropertySource(properties = "property.b=value-b")
class TestPropertySourceTests {
@Autowired
private Environment environment;
@Test
void testPropertiesFromTestPropertySourcesAreMergedFromTestAndMetaAnnotation() {
assertThat(environment.getProperty("property.a"), is(equalTo("value-a")));
assertThat(environment.getProperty("property.b"), is(equalTo("value-b")));
}
}
元注釋:
@Retention(RUNTIME)
@ExtendWith(SpringExtension.class)
@SpringBootTest
@TestPropertySource(properties = "property.a=value-a")
@interface CustomTest {
}
測試失敗,並且property.a
為null
而不是value-a
,這表明不存在通過元注釋定義的屬性。
如果兩個@TestPropertySource
批注將處於類層次結構中,則該方法同樣有效(即, TestPropertySourceTests
將從BaseTests
擴展而來, BaseTests
又在其自己的@TestPropertySource
定義property.a
)
這是預期的(和記錄的)行為嗎? 可能有人爭辯說,順序僅在類層次結構中定義,而不在注釋樹中定義,或在類層次結構和注釋樹之間定義。
這是因為當Spring引導您的測試上下文時,它將僅搜索org.springframework.test.context.TestPropertySource
類型的本地聲明注釋。
看看到TestPropertySourceUtils
這里 ,也看看到MetaAnnotationUtils
在這里
if (AnnotationUtils.isAnnotationDeclaredLocally(annotationType, clazz)) {
return new AnnotationDescriptor<>(clazz, clazz.getAnnotation(annotationType));
}
當他們立即返回結果,沒有機會也取你的@CustomTest
其聲明注釋@TestPropertySource
注釋。
因此,目前尚不可能。
這是春天設計的。 Sam Brannen在其他答案中證實了這一點:
我在Spring的跟蹤器中打開了一個問題: https : //github.com/spring-projects/spring-framework/issues/23299
如果您仍需要此功能,請對其投票。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.