为什么我的测试不能从其父级继承ContextConfiguration位置?

8

为了保持DRY(Don't Repeat Yourself)原则,我希望在一个父类中定义我的ContextConfiguration,并让所有的测试类都继承它,像这样:

父类:

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/org/my/Tests-context.xml")
public abstract class BaseTest {

}

子类:

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(inheritLocations = true)
public class ChildTest extends BaseTest {

    @Inject
    private Foo myFoo;

    @Test
    public void myTest() {
          ...
    }
}

根据ContextConfiguration文档,我应该能够继承父类的位置,但我无法使其工作。Spring仍在寻找默认位置(/org/my/ChildTest-context.xml)的文件,当找不到时会报错。我尝试了以下方法,但都不起作用:
  • 将父类变为具体类
  • 在父类中添加一个空操作测试
  • 在父类中添加注入成员
  • 上述方法的组合
我使用的是spring-test 3.0.7和JUnit 4.8.2。
1个回答

13

在子类上移除@ContextConfiguration(inheritLocations = true)注解。默认情况下,inheritLocations值为true。

如果您添加了@ContextConfiguration(inheritLocations = true)注解但未指定locations参数,则告诉Spring要通过添加默认上下文/org/my/ChildTest-context.xml来扩展资源位置列表。

尝试使用以下内容:

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
public class ChildTest extends BaseTest {

    @Inject
    private Foo myFoo;

    @Test
    public void myTest() {
          ...
    }
}

就是这样!这让我想起来,我需要去接受你的另一个答案。你正式成为本周的SO MVP :-) - Evan Haas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接