2011-07-01 241 views
8

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

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

如何加载上下文以使其自动装配?

回答

21

您是否在Spring参考文档中学习了Testing一章?下面是你应该开始一个例子:

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

    @Resource 
    private FooService fooService; 

    // class body... 
} 

如果你是在/src/test/javacom.example.MyTest,你将需要/src/test/resources/com/example/MyTest-context.xml - 但例外会告诉你的方式。

+1

+1 22秒:) – abalogh

+0

:-)我们的代码片段我们可疑的相似,我闻到我们都用过的相同的参考;-)。 –

+0

http://static.springsource.org/spring/docs/3.0.x/reference/testing.html,难怪:) – abalogh

5

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

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... 
} 

通常这是一个好主意,但有一个测试的ApplicationContext为您的测试基础设施。