@TestPropertySource测试类和元注释上的注释未合并



当在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.anull而不是value-a,表明通过元注释定义的属性不存在。

如果两个@TestPropertySource注释在类层次结构中(即TestPropertySourceTests将从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 在其他回答中证实了这一点:

  • https://stackoverflow.com/a/35748348
  • https://stackoverflow.com/a/26183692

我在Spring的跟踪器中打开了一个问题:https://github.com/spring-projects/spring-framework/issues/23299

如果您仍然需要该功能,请投票支持它。

最新更新