【问题标题】:Why can't my test inherit its ContextConfiguration location from its parent?为什么我的测试不能从其父级继承其 ContextConfiguration 位置?
【发布时间】:2013-01-18 17:04:37
【问题描述】:

为了 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) 和 barfs 中查找文件,但找不到它。我试过以下没有运气:

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

我正在进行春季测试 3.0.7 和 JUnit 4.8.2。

【问题讨论】:

    标签: java spring junit spring-test


    【解决方案1】:

    删除子类上的@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() {
              ...
        }
    }
    

    【讨论】:

    • 就是这样!这提醒了我,我需要去接受你的其他答案。你正式成为本周的 SO MVP :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2017-08-31
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多