@ActiveProfiles in meta annotation and on test class not working

夙愿已清 提交于 2019-11-28 01:20:05

问题


I created a meta annotation @EmbeddedMongoDBUnitTest that activates two profiles to be used in spring based unit tests. The basic setup works:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ActiveProfiles({"embeddedMongoDB", "embeddedMongoDBUnitTest"})
public @interface EmbeddedMongoDBUnitTest {
}

@RunWith(SpringJUnit4ClassRunner.class)
@EmbeddedMongoDBUnitTest
@ContextConfiguration(...)
public class WorkingTest {
    ...
}

Now when trying to activate another profile with another @ActiveProfiles annotation on the test class itself, the profiles in @EmbeddedMongoDBUnitTest aren't activated anymore:

@RunWith(SpringJUnit4ClassRunner.class)
@EmbeddedMongoDBUnitTest
@ActiveProfiles({"h2IntegrationTests"})
@ContextConfiguration(...)
public class NotWorkingTest {
    ...
}

Is there a reason why this is not working or is this a bug in the spring test code?


回答1:


This is not a bug: this is by design.

The reason this does not work is that this form of configuration is simply not supported by Spring.

The algorithm that the Spring Framework uses when searching for an annotation stops once it has found the first occurrence of the sought annotation. Thus, in your example, the @ActiveProfiles annotation on NotWorkingTest effectively shadows the @ActiveProfiles annotation on your composed @EmbeddedMongoDBUnitTest annotation.

Please note that these are the general semantics for annotations in the core Spring Framework. In other words, the behavior you are experiencing is not specific to the spring-test module.

Having said that, profiles declared via @ActiveProfiles are in fact inherited within a test class hierarchy (unless you set the inheritProfiles flag to false). But don't confuse class hierarchies with annotation hierarchies: Java supports inheritance for interfaces and classes but not for annotations.

Hope this clarifies things!

Sam (component lead for the spring-test module)



来源:https://stackoverflow.com/questions/26176038/activeprofiles-in-meta-annotation-and-on-test-class-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!