本文介绍了在元注解和测试类不工作@ActiveProfiles的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个注解元的@EmbeddedMongoDBUnitTest激活基于Spring的单元测试中使用两个配置文件。基本设置如下:

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 {
    ...
}

现在试图激活与测试类本身的另一个@ActiveProfiles标注其他配置文件时,在@EmbeddedMongoDBUnitTest的配置文件不再启动:

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 {
    ...
}

时有一个原因这不工作或者这是在春季测试code错误?

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

推荐答案

这是不是一个错误:这是由设计

This is not a bug: this is by design.

这不工作的原因是,这种形式的配置根本就不是由Spring支持。

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

一旦发现寻求注释中第一次出现了Spring框架的注解搜索时使用的算法停止。因此,在你的榜样,在 @ActiveProfiles 注释 NotWorkingTest 有效地屏蔽了该 @ActiveProfiles 您构成 @EmbeddedMongoDBUnitTest 注解注释。

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.

请注意,这些是在核心Spring框架注解一般语义。换句话说,你所遇到的行为不是具体到弹簧试验模块。

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.

说了这么多,通过 @ActiveProfiles 宣布型材实际上的继承的测试类层次结构中(除非你设置 inheritProfiles 标志)。但是,不要混淆类层次结构与层次注释:Java支持的接口和类而不是继承的注释

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.

希望这澄清的事情!

山姆(元件引线的弹簧试验模块)

Sam (component lead for the spring-test module)

这篇关于在元注解和测试类不工作@ActiveProfiles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:38
查看更多