春季junit测试

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

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

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

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

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class MyTest { @Resource private FooService fooService; // class body... } 

如果您在/src/test/java中的com.example.MyTest中,则需要/src/test/resources/com/example/MyTest-context.xml – 但exception将向您显示方式。

这是一种可能性:

 @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是个好主意。

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