将基于 Spring 3.0.0 java 的 IOC 添加到 JUnit 4.7 测试
有一个文档 http://static.springsource.org/spring /docs/2.5.6/reference/testing.html 如何使用 xml 配置向 junit 测试添加 IoC 支持,但我找不到基于 java 的配置示例...
例如,我有 java- based bean:
public class AppConfig
{
@Bean
public Test getTest() { return new Test(); }
}
和测试:
@RunWith(SpringJUnit4ClassRunner.class)
public class IocTest
{
@Autowired
private Test test;
@Test
public void testIoc()
{
Assert.assertNotNull(test);
}
}
我应该添加什么才能在不使用 xml-configs 的情况下在 junit 测试中启用基于 java 的 bean?
通常我使用:
new AnnotationConfigApplicationContext(AppConfig.class);
但它不适用于测试......
There is a doc http://static.springsource.org/spring/docs/2.5.6/reference/testing.html how to add IoC support to junit tests using xml-configuration, but I can not find example for java-based configuration...
For example, I have java-based bean:
public class AppConfig
{
@Bean
public Test getTest() { return new Test(); }
}
And test:
@RunWith(SpringJUnit4ClassRunner.class)
public class IocTest
{
@Autowired
private Test test;
@Test
public void testIoc()
{
Assert.assertNotNull(test);
}
}
What should I add to enable java-based beans to my junit test without using xml-configs?
Normally I use:
new AnnotationConfigApplicationContext(AppConfig.class);
but it does not work for tests...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新: Spring 3.1将开箱即用地支持它,请参阅Spring 3.1 M2:使用@Configuration类和配置文件进行测试。
Spring似乎还不支持这个功能。
不过,它可以很容易地实现:
-
-
Update: Spring 3.1 will support it out of the box, see Spring 3.1 M2: Testing with @Configuration Classes and Profiles.
It seems to be this feature is not supported by Spring yet.
However, it can be easily implemented:
-
-
如果您获得空值,则可能没有加载应用程序上下文。
请注意,默认情况下,运行程序从“classpath:/com/test/IocTest-context.xml”加载它(假设 IocTest.java 包是 com.test)
如果不存在,请尝试通过添加来指定它
If you are getting a null value probably it's not loading the application context.
Note that by default it the runner loads it from "classpath:/com/test/IocTest-context.xml" (assuming IocTest.java package is the com.test)
If it is not there try specifying it by adding
一般来说,为什么这不起作用(断言失败):
日志输出:
Genereally, why this does not work (assert fails):
Log output:
这对我有用......
取自 http://www.swiftmind.com/de/2011/06/22/spring-3-1-m2-testing-with-configuration-classes-and-profiles/< /a>
This is what worked for me...
Taken from http://www.swiftmind.com/de/2011/06/22/spring-3-1-m2-testing-with-configuration-classes-and-profiles/