Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring Spring services into JUnit tests

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?

like image 635
orwe Avatar asked Jan 05 '15 12:01

orwe


2 Answers

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

like image 167
bachr Avatar answered Oct 10 '22 23:10

bachr


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.

like image 35
ognjenkl Avatar answered Oct 11 '22 01:10

ognjenkl