Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowired, @Component and testing

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?

like image 408
Ran Biron Avatar asked Jul 12 '11 20:07

Ran Biron


People also ask

Is @component required for Autowired?

Injection and autowiring do not require @Component .

Can we Autowire @component class?

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.

What is @component and @autowired in spring boot?

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.

Can we use Autowired in test class?

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.


1 Answers

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.

like image 187
Tomasz Nurkiewicz Avatar answered Oct 02 '22 10:10

Tomasz Nurkiewicz