问题
I have an old app built with an ancient version of Spring: 2.0.7. I have been tasked with adding new functionality to this app, so I'm required to write some JUnit tests too.
So far, I have writen mockup classes for my services, and an applicationContext-test.xml
file placed under src/test/resources/
. Typically, the next step would be to write my test case like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class MyTestCase {
...
}
But as I read, the Spring TestContext Framework was first introduced in Spring 2.5, and therefore it's not available to me.
Is there any other way in which I can load the applicationContext.xml file within JUnit, and access the beans defined in that XML file?
Since I already have the mockups and they don't require initialization parameters, I could just instantiate them and pass them to the setter, maybe using the @BeforeClass
annotation. But I would prefer using the Spring context, if possible, given that I ended up with a somehow unusual way to load the beans and it should be tested too...
回答1:
I ended writing an ApplicationContext wrapper, and calling the init
method myself with a @Before
annotation, instead of relying on Spring to do that. This way, I can test my initialization method as if it was called from 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());
}
// ...
}
(I still want to know if there is a better way of doing this, without the Spring 2.5+ annotations).
来源:https://stackoverflow.com/questions/48337031/how-can-i-test-an-old-spring-2-0-7-application-with-junit