Java 春季junit测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6546871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
spring junit testing
提问by Massive Boisson
I have a maven spring project (latest version) and I want to write some junit tests (latest version).
我有一个 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 bean 是自动装配的,当我从 junit 测试中调用它们时,我得到空指针异常,因为 spring 不会自动装配它们。
How can I load the context so that things are autowired?
如何加载上下文以便自动装配?
采纳答案by Tomasz Nurkiewicz
Have you studied Testingchapter in Spring reference documentation? Here is an example you should start with:
您是否学习过 Spring 参考文档中的测试章节?这是您应该从以下示例开始:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {
@Resource
private FooService fooService;
// class body...
}
If you are in com.example.MyTest
in /src/test/java
, you will need /src/test/resources/com/example/MyTest-context.xml
- but the exceptions will show you the way.
如果您在com.example.MyTest
中/src/test/java
,您将需要/src/test/resources/com/example/MyTest-context.xml
- 但例外情况会为您指明方向。
回答by artbristol
You should use the SpringJUnit4ClassRunner
on your test classes, and use @Resource
(or @Autowired
) on the field in your test class that contains the bean. You should consider having a special test context Spring configuration that uses stubs so that your tests are genuine unit tests, and don't rely on the whole application context.
您应该SpringJUnit4ClassRunner
在测试类上使用 ,并在包含 bean 的测试类中的字段上使用@Resource
(或@Autowired
)。您应该考虑拥有一个使用存根的特殊测试上下文 Spring 配置,以便您的测试是真正的单元测试,而不依赖于整个应用程序上下文。
回答by abalogh
This is a possibility:
这是一种可能性:
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml"
// in the root of the classpath
@ContextConfiguration({"/applicationContext.xml"})
public class MyTest {
// class body...
}
Usually it's a good idea though to have a test-applicationContext for your test infrastructure.
通常,为您的测试基础设施设置一个 test-applicationContext 是个好主意。