gpt4 book ai didi

spring - 元注释和测试类中的@ActiveProfiles 不起作用

转载 作者:行者123 更新时间:2023-12-04 18:06:23 27 4
gpt4 key购买 nike

我创建了一个元注释@EmbeddedMongoDBUnitTest,它激活了两个要在基于 Spring 的单元测试中使用的配置文件。基本设置有效:

@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 测试代码中的错误?

最佳答案

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

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

Spring 框架在搜索注解时使用的算法在找到所查找注解的第一次出现后停止。因此,在您的示例中,@ActiveProfiles注释 NotWorkingTest有效遮蔽 @ActiveProfiles对您撰写的 @EmbeddedMongoDBUnitTest 进行注释注解。

请注意,这些是核心 Spring Framework 中注释的一般语义。换句话说,您遇到的行为并非 spring-test 所特有的。模块。

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

希望这能澄清事情!

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

关于spring - 元注释和测试类中的@ActiveProfiles 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26176038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com