spring java配置单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8640969/
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 java configuration unit test
提问by user373201
I am trying out spring's java configuration. While using xml config files my unit tests use to have the following
我正在尝试 spring 的 java 配置。在使用 xml 配置文件时,我的单元测试使用以下内容
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(....)
If I am using java configuration, How do i do it. or should I just use
如果我使用的是 java 配置,我该怎么做。或者我应该使用
ApplicationContext appConfig = new AnnotationConfigApplicationContext(SimpleConfiguration.class);
回答by Chris Beams
As of Spring 3.1, @ContextConfiguration now has full support for @Configuration classes; no XML required.
从 Spring 3.1 开始,@ContextConfiguration 现在完全支持 @Configuration 类;不需要 XML。
Or more specifically, http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#testcontext-ctx-management-javaconfig, which shows the following code snippet:
或者更具体地说,http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#testcontext-ctx-management-javaconfig,它显示了以下内容代码片段:
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes={AppConfig.class, TestConfig.class})
public class MyTest {
// class body...
}
AppConfigand TestConfigare @Configuration classes (aka "Java config" classes in @user373201's comments)
AppConfig并且TestConfig是@Configuration 类(在@user373201 的评论中也称为“Java 配置”类)
回答by Aravind A
@ContextConfiguration is used to load the Spring configurations while you are working with test cases . If you don't need it , you could use ClassPathXmlApplicationContext to load the Spring configuration .
@ContextConfiguration 用于在您处理测试用例时加载 Spring 配置。如果不需要,可以使用 ClassPathXmlApplicationContext 加载 Spring 配置。
Use the constructorwhich takes in configuration locations as String array .
使用接受配置位置作为 String array的构造函数。
AnnotationConfigApplicationContext is used to auto detect the annotated classes . I don't think it can be used to load configuration files . It is similar to context:component-scan
AnnotationConfigApplicationContext 用于自动检测带注释的类。我认为它不能用于加载配置文件。它类似于 context:component-scan
SpringJUnit4ClassRunnerprovides Spring Test support for Junit via annotations like @Test.
SpringJUnit4ClassRunner通过 @Test 之类的注解为 Junit 提供 Spring Test 支持。

