mercredi 1 juillet 2020

How to inject Beans inside a test class propperly with spring boot and annotations

I have a class I want to test if it uses the right Beans when a certain profile is active. Therefore I have written a test class, with the profile active, for the DomesticService (wich in turn uses the GardeningService and CleaningService, all of it is autowired).

@Component
public class HumanDomesticService implements DomesticService {
    private CleaningService cleaningService;
    private GardeningService gardeningService;
    private Logger logger;

    HumanDomesticService() {
    }

    @Autowired
    public HumanDomesticService(CleaningService cleaningService, GardeningService gardeningService, Logger logger) {
        setCleaningService(cleaningService);
        setGardeningService(gardeningService);
        setLogger(logger);
    }

I made a test configuration class, wich should scan the whole project for Beans, since the SpringBootApplication annotation includes the ComponentScan annotation.

@SpringBootApplication
public class ActiveProfileConfig {
}

Yet my test class can't seem to find the right Beans to complete the test.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'be.mycompany.springlessons.housekeeping.domestic.service.ActiveProfileSmallHouseTest': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'be.mycompany.springlessons.housekeeping.domestic.service.DomesticService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

After that I tried to make Beans inside my configuration class, which makes my tests succeed, but then Maven complains about finding 2 Beans wich could be injected there. Maven seems to be able to see all the beans through the ComponentScan.

Finally I ended importing the necessary classes, which works for both my tests and Maven, but it just doesn't seem to be the right and best solution.

@SpringBootTest(classes = ActiveProfileConfig.class)
@ActiveProfiles(profiles = "smallHouse")
@Import({HumanDomesticService.class, HumanCleaningService.class, RobotCleaningService.class, HumanGardeningService.class, HedgeTrimmerFactory.class, Broom.class, VacuumCleaner.class,
        Sponge.class, DisposableDuster.class, LawnMower.class, LoggerFactory.class})
public class ActiveProfileSmallHouseTest {
    @Autowired
    private DomesticService service;

I have tried to search on the internet for another solution and saw I wasn't the only one with the problem, but no other solution seemed yet to have worked.

What is the reason ComponentScan doesn't seem to work in a test class and how best to solve this?

Aucun commentaire:

Enregistrer un commentaire