Jordi
Jordi

Reputation: 23237

Spring inject test: Bean is not injected on test

I've created this custom test configuration:

@TestConfiguration
public static class RestTemplateTestConfiguration {

    @Bean
    @Primary
    public static ApplicationDao applicationDao() {
        ApplicationDao mock = Mockito.mock(ApplicationDao.class);
        // some stuff code
        return mock;
    }
}

I've set a breakpoint on applicationDao, but it's never reached, and therefore mock is never injected.

EDIT

ApplicationDao is an @Repository annotated class:

@Repository
public interface ApplicationDao extends MongoRepository<Application, String> {

So, how could I override this @Repository annotated AplicationDao?

Currently, I'm getting this message when spring starts:

Skipping bean definition for [BeanMethod:name=applicationDao,declaringClass=net.gencat.transversal.espaidoc.functional.references.GroupReferencesTest$RestTemplateTestConfiguration]: a definition for bean 'applicationDao' already exists. This top-level bean definition is considered as an override.

Any ideas?

Upvotes: 0

Views: 99

Answers (1)

Adina Rolea
Adina Rolea

Reputation: 2109

If your method applicationDao() is never called it means that your spring boot is not scanning the package where RestTemplateTestConfiguration is located.

The simplest solutions is to move the configuration under the same package (or its children) as the one that contains the class annotated with @SpringBootApplication.

OBS : This rule applies even though the configuration is in the test directory instead of main.

Another solution is to add @ComponentScan with the configuration package or to use @Import(RestTemplateTestConfiguration.class) at your spring boot test level.

SUGGESTION: For your problem you can use:

@Mock
ApplicationDao applicationDao;

and if you have another service that uses this one to use:

@InjectMock
MyService myService;

Upvotes: 1

Related Questions