Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

spring - @ActiveProfiles in meta annotation and on test class not working

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...