Spring boot test: MockedBean conflicts with others

1.7k views Asked by At

Currently, I've two RestTemplate beans:

@Bean
@Primary
public RestTemplate jwtRestTemplate(
    RestTemplateBuilder builder,
    JWTService jwtService) {

        return builder
            .additionalInterceptors(
                Collections.singletonList(
                    new JWTHeaderRequestInterceptor(jwtService)
                )
            )
            .build();
}

@Bean
public RestTemplate rawRestTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

The first one is primary and the other one is requested by @Qualifier("rawRestTemplate").

However, I'm mocking a ResTemplate into my tests:

@RunWith(SpringRunner.class)
@SpringBootTest()
public class AuditoryTest {

    @MockBean()
    private RestTemplate frontOfficeRestTemplate;

    @Autowired
    private DocumentServiceBackOffice documentService;

DocumentServiceBackOffice constructor is:

public DocumentServiceBackOffice(RestTemplate restTemplate);

I'm getting an exception:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in net.gencat.transversal.espaidoc.backoffice.service.DocumentServiceBackOffice required a single bean, but 2 were found:
    - rawRestTemplate: defined by method 'rawRestTemplate' in class path resource [net/gencat/transversal/espaidoc/backoffice/config/BackOfficeConfiguration.class]
    - jwtRestTemplate: defined by method 'createMock' in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Message is pretty clear, but I don't quite figure out how to solve that.

Any ideas?

1

There are 1 answers

1
Jordi On

I've solved that using that additional Configuration class:

@TestConfiguration
public static class RestTemplateTestConfiguration {

    @Bean("jwtRestTemplate")
    @Primary
    public static RestTemplate someService() {
        return Mockito.mock(RestTemplate.class);
    }
}