Vla*_*nco 11 java junit spring
有一个文档http://static.springsource.org/spring/docs/2.5.6/reference/testing.html如何使用xml-configuration为junit测试添加IoC支持,但我找不到基于java的示例组态...
例如,我有基于java的bean:
public class AppConfig
{
@Bean
public Test getTest() { return new Test(); }
}
Run Code Online (Sandbox Code Playgroud)
并测试:
@RunWith(SpringJUnit4ClassRunner.class)
public class IocTest
{
@Autowired
private Test test;
@Test
public void testIoc()
{
Assert.assertNotNull(test);
}
}
Run Code Online (Sandbox Code Playgroud)
在不使用xml-configs的情况下,我应该添加什么来启用基于java的bean到我的junit测试?
通常我使用:
new AnnotationConfigApplicationContext(AppConfig.class);
Run Code Online (Sandbox Code Playgroud)
但它不适用于测试......
更新: Spring 3.1将支持开箱即用,请参阅Spring 3.1 M2:使用@Configuration类和配置文件进行测试.
似乎Spring尚未支持此功能.但是,它可以很容易地实现:
public class AnnotationConfigContextLoader implements ContextLoader {
public ApplicationContext loadContext(String... locations) throws Exception {
Class<?>[] configClasses = new Class<?>[locations.length];
for (int i = 0; i < locations.length; i++) {
configClasses[i] = Class.forName(locations[i]);
}
return new AnnotationConfigApplicationContext(configClasses);
}
public String[] processLocations(Class<?> c, String... locations) {
return locations;
}
}
Run Code Online (Sandbox Code Playgroud)
-
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
value = "com.sample.AppConfig")
public class IocTest {
@Autowired
TestSerivce service;
@Test
public void testIoc()
{
Assert.assertNotNull(service.getPredicate());
}
}
Run Code Online (Sandbox Code Playgroud)
-
@Configuration
public class ApplicationConfig
{
...
@Bean
public NotExistsPredicate getNotExistsPredicate()
{
return new NotExistsPredicate();
}
@Bean
public TestService getTestService() {
return new TestService();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6273 次 |
| 最近记录: |