How would you go about integration testing a spring application that is annotation-configured and component-scanned and does not have an XML configuration at all? I'm hitting a wall with the need to replace production components with testing components without actually resorting to xml configuration or reflection injections to all the @autowired parts.
Example:
interface A {...}
@Component
class AImpl implements A {
...
}
interface B {...}
@Component
class BImpl implements B {
@Autowired A a;
...
}
interface C {...}
class CImpl implements C {
@Autowired B b;
...
}
then in my test I want to use ATestImpl, but I only have access to C (integration testing C).
How would you go about doing that?
Injection and autowiring do not require @Component .
I use @Autowired in the attribute network of the classes Account and Agreement , but it is autowired only in the class Agreement but not in Account . The @ComponentScan runs over the 3 needed packages.
Enable @Autowired in Spring Boot In the spring boot application, all loaded beans are eligible for auto wiring to another bean. The @Component annotation is used to load a java class as a bean. All classes with annotation such as @Component, @bean etc are auto-wired in the spring boot application.
To check the Service class, we need to have an instance of the Service class created and available as a @Bean so that we can @Autowire it in our test class. We can achieve this configuration using the @TestConfiguration annotation.
Take advantage of @Primary annotation:
@Service
@Primary
public class TestA implements A {
//...
}
If there is more than one bean implementing A, Spring will prefer the one annotated with @Primary. If you place TestA class in /src/test/java, it will only be picked up during test execution, on normal context startup Spring won't see TestA and use only avaialble AImpl.
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