Autowiring Spring services into JUnit tests

orwe picture orwe · Jan 5, 2015 · Viewed 14.6k times · Source

Following is the service.

@Service
public class MyService  {
   public List<Integer> getIds(Filter filter){
      // Method body
   }
}

And a configuration class.

@Configuration
public static class MyApplicationContext {

    @Bean
    public Filter filter(ApplicationContext context) {
        return new Filter();
    }
}

The desired goal is a unit test to confirm getIds() returns the correct result. See the JUnit test below.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MyApplicationContext.class,                                                   
                      loader=AnnotationConfigContextLoader.class)
public class AppTest
{
    @Autowired
    Filter filter;

    @Autowired
    MyService service;
}

The compiler finds the correct bean for the Filter class but throws a BeanCreationException: Could not autowire field exception for the service variable. I've tried adding the service class to the ContextConfiguration classes attribute but that results in a IllegalStateException: Failed to load ApplicationContext exception.

How can I add MyService to ContextConfiguration?

Answer

bachr picture bachr · Jan 5, 2015

Add the following annotation to MyApplicationContext for the service to be scanned @ComponentScan("myservice.package.name")