
[英]How can I turn this 'spring 3.1' oriented junit4 test with SpringJUnit4ClassRunner into a spring oriented junit3.8 based test?
[英]How can I test an old Spring 2.0.7 application with JUnit?
我有一个使用旧版本的Spring构建的旧应用:2.0.7。 我的任务是向该应用程序添加新功能,因此也需要编写一些JUnit测试。
到目前为止,我已经为我的服务编写了模型类,并在src/test/resources/
下放置了一个applicationContext-test.xml
文件。 通常,下一步是这样编写我的测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class MyTestCase {
...
}
但是据我所读, Spring TestContext Framework是在Spring 2.5中首次引入的 ,因此它对我不可用。
还有什么其他方法可以在JUnit中加载applicationContext.xml文件,并访问在该XML文件中定义的bean?
因为我已经有了模型,并且它们不需要初始化参数,所以我可以实例化它们,然后将它们传递给setter,也许使用@BeforeClass
批注。 但是如果可能的话,我宁愿使用Spring上下文,因为我最终以某种不寻常的方式加载了bean,并且也应该对其进行测试...
我结束了编写ApplicationContext包装器,并使用@Before
注释自己调用了init
方法,而不是依靠Spring来执行此操作。 这样,我可以测试初始化方法, 就像从Spring调用它一样 。
public class ApplicationContextMock implements ApplicationContext {
private Map<String, Object> beans;
public ApplicationContextMock() {
beans = new HashMap<String, Object>();
beans.put("child1", new SomeServiceMock());
beans.put("child2", new AnotherServiceMock());
}
public Object getBean(String arg0) throws BeansException {
return beans.get(arg0);
}
// ...
}
@RunWith(JUnit4.class)
public class MyTestCase {
MyClass foo;
@Before
public void init() {
foo = new MyClass();
foo.loadChildren(new ApplicationContextMock());
}
// ...
}
(我仍然想知道如果没有Spring 2.5+注释,是否还有更好的方法来实现)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.