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

时间:2018-08-15 10:06:01

标签: spring spring-boot

在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注释将处于类层次结构中(即TestPropertySourceTestsBaseTests扩展而来,则property.a依次在其自己的{{1 }})

这是预期的(和记录的)行为吗?有人可能会争辩说,顺序仅在类层次结构中定义,而不是在注释树中定义,或在类层次结构和注释树之间定义。

2 个答案:

答案 0 :(得分:0)

这是因为当Spring引导您的测试上下文时,它将仅搜索org.springframework.test.context.TestPropertySource类型的本地声明的注释。

看看TestPropertySourceUtils here 还可以查看here

中的MetaAnnotationUtils
    if (AnnotationUtils.isAnnotationDeclaredLocally(annotationType, clazz)) {
        return new AnnotationDescriptor<>(clazz, clazz.getAnnotation(annotationType));
    }

当它们立即返回结果时,就没有机会同时使用声明的@CustomTest注释来获取@TestPropertySource注释。

所以目前不可能。

答案 1 :(得分:0)

这是春天设计的。 Sam Brannen在其他答案中证实了这一点:

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

如果仍需要此功能,请投票。

相关问题