【问题标题】:@ActiveProfiles in meta annotation and on test class not working元注释和测试类中的@ActiveProfiles 不起作用
【发布时间】:2014-11-28 08:10:02
【问题描述】:

我创建了一个元注释@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 {
    ...
}

是否有原因导致这不起作用或者这是弹簧测试代码中的错误?

【问题讨论】:

    标签: spring junit annotations spring-annotations spring-test


    【解决方案1】:

    这不是错误:这是设计使然。

    这不起作用的原因是Spring根本不支持这种形式的配置。

    Spring 框架在搜索注解时使用的算法在找到所查找注解的第一次出现后停止。因此,在您的示例中,NotWorkingTest 上的 @ActiveProfiles 注释有效地隐藏了您组合的 @EmbeddedMongoDBUnitTest 注释上的 @ActiveProfiles 注释。

    请注意,这些是核心 Spring 框架中注解的一般语义。换句话说,您遇到的行为并非特定于 spring-test 模块。

    话虽如此,通过@ActiveProfiles 声明的配置文件实际上继承在测试类层次结构中(除非您将inheritProfiles 标志设置为false)。但不要将类层次结构与注解层次结构混淆:Java 支持接口和类的继承,但不支持注解。

    希望这可以澄清事情!

    Sam(spring-test 模块的组件负责人)

    【讨论】:

    • 感谢山姆的探索。如果这不是错误,我在这里质疑设计。 spring 框架只搜索第一个注释可能是真的,但在这种情况下,人们真的希望所有@ActiveProfiles 注释都被拾取,尤其是。如果它支持类继承。
    • James,请随时在 jira.spring.io 创建 JIRA 问题以请求此类功能,我们会考虑。
    • @SamBrannen 有没有关于这个问题的 JIRA 票?我还没找到呢
    • 现在是时候说自 Spring 4 以来这种情况发生了变化,@ActiveProfiles 是一个元注释
    • @ActiveProfiles 本身不是元注释。这是一个注释,可以从 Spring 4 开始用作元注释。但是,OP 显然已经在使用 Spring 4+,因为他的 @EmbeddedMongoDBUnitTest 是独立工作的。
    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    相关资源
    最近更新 更多