Autowire a Spring service in JUnit test

I have the following Spring service:

@Service public class MyService { public List<int> getIds(Filter filter){ ... } } 

and configuration class:

 @Configuration public static class MyApplicationContext { @Bean public Filter filter(ApplicationContext context) { return new Filter(); } } 

Now I would like to create a unit test to check if the getIds method returns the correct results. I created the following JUnit test:

 @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 tried to add a service class to ContextConfiguration.classes, but then the compiler threw the exception "Unblocked exception: Failed to load ApplicationContext".

How to enable MyService in ContextConfiguration?

+6
source share
1 answer

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

+8
source

Source: https://habr.com/ru/post/980529/


All Articles