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?
Add the following annotation to MyApplicationContext
for the service to be scanned @ComponentScan("myservice.package.name")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With