@ActiveProfiles in meta annotation and on test cla

2019-02-14 23:23发布

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条回答
不美不萌又怎样
2楼-- · 2019-02-15 00:12

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)

查看更多
登录 后发表回答