从元注释重写 ContextHierarchy 和 ContextConfiguration
-
23-12-2019 - |
题
我们有使用元注释的测试类:
@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(locations = {"/web/WEB-INF/spring.xml" }, name = "parent"),
@ContextConfiguration("/web/WEB-INF/spring-servlet.xml")
})
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseSpringTest {
}
但希望能够覆盖或附加到测试类本身的层次结构元素,例如:
@BaseSpringTest
@ContextConfiguration(locations = {"/web/WEB-INF/spring-extension.xml" }, name = "parent")
public class MyTest extends AbstractTestNGSpringContextTests {
...
}
到目前为止,这对我们来说还没有奏效......是否有任何机制可以实现这一点?我发现 https://jira.spring.io/browse/SPR-11038, ,但我认为这并不是解决此类情况的方法。
谢谢!
解决方案
是否有任何机制可以实现这一点?
不,没有这样的机制支持这种配置风格。
风俗 组合注释 可以使用 代替 实际的注释, 不与 实际的注释。在核心 Spring 框架中都是如此(也许除了 @Profile
和 @Conditional
).
换句话说,你不能声明 @ContextConfiguration
和另一个元注释的注释 @ContextConfiguration
(例如,您的 @BaseSpringTest
)在同一个班级。如果这样做,您会发现 Spring 只找到这些声明之一。
但是,如果您引入基类,您就可以实现您的目标(尽管需要扩展该基类):
@BaseSpringTest
public abstract class AbstractBaseTests extends AbstractTestNGSpringContextTests {
// ...
}
@ContextConfiguration(locations = {"/web/WEB-INF/spring-extension.xml" }, name = "parent")
public class MyTest extends AbstractBaseTests {
// ...
}
当然,如果您要走“基类”路线,则自定义组合注释对您来说可能没那么有用。
问候,
Sam(Spring TestContext 框架的作者)
不隶属于 StackOverflow