Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Spring 3.0.0 java based IOC to JUnit 4.7 tests

Tags:

java

junit

spring

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...

like image 574
Vladimir Mihailenco Avatar asked Feb 09 '10 11:02

Vladimir Mihailenco


1 Answers

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();
    }
}
like image 144
axtavt Avatar answered Oct 24 '22 10:10

axtavt