我创建了一个元注释@EmbeddedMongoDBUnitTest,它激活了两个配置文件,用于基于弹簧的单元测试。基本设置有效:
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ActiveProfiles({"embeddedMongoDB", "embeddedMongoDBUnitTest"})
public @interface EmbeddedMongoDBUnitTest {
}
@RunWith(SpringJUnit4ClassRunner.class)
@EmbeddedMongoDBUnitTest
@ContextConfiguration(...)
public class WorkingTest {
...
}
现在,当尝试使用测试类本身上的另一个@ActiveProfiles注释激活另一个配置文件时,@ EmbeddedMongoDBUnitTest中的配置文件不再被激活:
@RunWith(SpringJUnit4ClassRunner.class)
@EmbeddedMongoDBUnitTest
@ActiveProfiles({"h2IntegrationTests"})
@ContextConfiguration(...)
public class NotWorkingTest {
...
}
有没有理由说这不起作用,或者这是春季测试代码中的错误?
答案 0 :(得分:7)
这不是错误:这是设计的。
这不起作用的原因是Spring不支持这种配置形式。
Spring Framework在搜索注释时使用的算法在找到第一次出现的搜索注释后停止。因此,在您的示例中,@ActiveProfiles
上的NotWorkingTest
注释会有效地隐藏撰写的@ActiveProfiles
注释上的@EmbeddedMongoDBUnitTest
注释。
请注意,这些是核心Spring Framework中注释的一般语义。换句话说,您遇到的行为并非特定于spring-test
模块。
话虽如此,通过@ActiveProfiles
声明的配置文件实际上是在测试类层次结构中继承(除非您将inheritProfiles
标志设置为false
)。但是,不要将类层次结构与注释层次结构混淆:Java支持接口和类的继承,但不支持注释。
希望这能澄清事情!
Sam(spring-test
模块的组件负责人)