0

我有一个用旧版 Spring 构建的旧应用程序:2.0.7。我的任务是向这个应用程序添加新功能,所以我也需要编写一些 JUnit 测试。

到目前为止,我已经为我的服务编写了模型类,并applicationContext-test.xmlsrc/test/resources/. 通常,下一步是编写我的测试用例,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class MyTestCase {
    ...
}

但正如我所读到的,Spring TestContext 框架是在 Spring 2.5 中首次引入的,因此我无法使用它。

有没有其他方法可以在 JUnit 中加载 applicationContext.xml 文件,并访问该 XML 文件中定义的 bean?

由于我已经有了模型并且它们不需要初始化参数,我可以将它们实例化并将它们传递给设置器,也许使用@BeforeClass注释。但如果可能的话,我更喜欢使用 Spring 上下文,因为我最终以一种不寻常的方式来加载 bean,并且它也应该被测试......

4

1 回答 1

0

我结束了编写 ApplicationContext 包装器,并init使用注释自己调用该方法@Before,而不是依赖 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+ 注释)。

于 2018-01-19T10:10:03.233 回答