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

时间:2013-01-18 17:04:38

标签: java spring junit spring-test

为了DRY的利益,我想在父类中定义我的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)和barf时,它仍在寻找文件。我试过以下没有运气:

  • 使父类具体化
  • 向父类添加无操作测试
  • 将注入的成员添加到父类
  • 上述
  • 的组合

我正在使用spring-test 3.0.7和JUnit 4.8.2。

1 个答案:

答案 0 :(得分:13)

删除子类的@ContextConfiguration(inheritLocations = true)。默认情况下,inheritLocations设置为true。

通过添加@ContextConfiguration(inheritLocations = true)注释而不指定位置,您告诉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() {
          ...
    }
}