繁体   English   中英

spring junit 测试

[英]spring junit testing

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

The issue I have is that my spring beans are autowired, and when I call them from junit test, I get null pointer exceptions, as spring doesn't autowire them.

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

您是否学习过 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 - 但异常会告诉您方法。

这是一种可能:

@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 的测试 class 的字段上使用@Resource (或@Autowired )。 您应该考虑有一个特殊的测试上下文 Spring 配置使用存根,以便您的测试是真正的单元测试,并且不依赖于整个应用程序上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM