Autowiring Spring services into JUnit tests
Asked Answered
P

2

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?

Phobe answered 5/1, 2015 at 12:49 Comment(2)
paste full stack trace please? And have you defined any beans in xml as well would help (if any)Colosseum
You have to tell spring to scan for @Service annotationsParameter
O
12

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

Outfit answered 5/1, 2015 at 12:55 Comment(0)
M
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.

Milewski answered 7/7, 2020 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.