14

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?

mtotowamkwe
  • 2,407
  • 2
  • 12
  • 19
orwe
  • 233
  • 1
  • 3
  • 10
  • paste full stack trace please? And have you defined any beans in xml as well would help (if any) – SMA Jan 05 '15 at 12:51
  • You have to [tell spring](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html) to scan for `@Service` annotations –  Jan 05 '15 at 12:51

2 Answers2

12

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

bachr
  • 5,780
  • 12
  • 57
  • 92
3

Add these two annotations to the test class AppTest, like in the following example:

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

@SpringBootTest loads the whole context.

ognjenkl
  • 1,407
  • 15
  • 11