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...
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:
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;
}
}
-
@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());
}
}
-
@Configuration
public class ApplicationConfig
{
...
@Bean
public NotExistsPredicate getNotExistsPredicate()
{
return new NotExistsPredicate();
}
@Bean
public TestService getTestService() {
return new TestService();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With