JUnit中的ContextConfiguration继承

4
我正在尝试模拟一个从redis获取数据的服务。我已经在spring上下文中注入了bean,放在了新的上下文文件test-context.xml中。但是我还有其他的上下文文件A.xml和B.xml,它们引用了test-context.xml中bean的方法。我在这里阅读了相关问题。
其中提到创建了一个BaseTest类,但当我继承该类时,子类中的上下文文件会首先被加载,而不是应该先加载基类的上下文文件,因为子类上下文中的bean依赖于基类上下文中的bean。
 @ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" }) 
 public abstract class myBaseTest { 
 @Before
 public void init() {
    // custom initialization code for resources loaded by testContext.xml 
 }

 @After
public void cleanup() {
    // custom cleanup code for resources loaded by testContext.xml
}
}

 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations = { "/META-INF/spring/A.xml",
                                 "/META-  INF/spring/B.xml" }) 
 public class childTest extends myBaseTest { ... }

这不是你问题的答案,但请看这篇文章以了解为什么不在测试系统中使用继承:http://www.petrikainulainen.net/programming/unit-testing/3-reasons-why-we-should-not-use-inheritance-in-our-tests/ - Vihar
1个回答

1
你可以将父级上下文添加到子级配置中。
 @ContextConfiguration(locations = { "/META-INF/spring/testContext.xml",
                             "/META-INF/spring/A.xml",
                             "/META-INF/spring/B.xml"}) 

如果您不覆盖它们,带有 @Before 和 @After 的方法将正常工作。

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