春季junit测试

时间:2011-07-01 10:40:07

标签: java unit-testing spring junit

我有一个maven spring项目(最新版本),我想写一些junit测试(最新版本)。

我遇到的问题是我的spring bean是自动装配的,当我从junit测试中调用它们时,我得到空指针异常,因为spring不会自动装配它们。

如何加载上下文以便自动连接?

3 个答案:

答案 0 :(得分:21)

你有没有研究过Spring参考文档中的Testing章节?这是一个你应该开始的例子:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Resource
    private FooService fooService;

    // class body...
}

如果您位于com.example.MyTest的{​​{1}},则需要/src/test/java - 但例外情况会向您显示。

答案 1 :(得分:12)

这是一种可能性:

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml"
// in the root of the classpath
@ContextConfiguration({"/applicationContext.xml"})
public class MyTest {
// class body...
}

通常,为测试基础架构提供test-applicationContext是个好主意。

答案 2 :(得分:5)

您应该在测试类上使用SpringJUnit4ClassRunner,并在包含该bean的测试类中的字段上使用@Resource(或@Autowired)。您应该考虑使用特殊的测试上下文Spring配置,它使用存根,以便您的测试是真正的单元测试,而不是依赖于整个应用程序上下文。