春季启动测试:MockedBean与他人发生冲突

时间:2018-10-08 15:11:12

标签: spring spring-boot spring-test springmockito

当前,我有两个RestTemplate bean:

@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();
}

第一个是主服务器,另一个是@Qualifier("rawRestTemplate")请求。

但是,我在测试中模拟了ResTemplate

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

    @MockBean()
    private RestTemplate frontOfficeRestTemplate;

    @Autowired
    private DocumentServiceBackOffice documentService;

DocumentServiceBackOffice的构造函数是:

public DocumentServiceBackOffice(RestTemplate restTemplate);

我要例外:

***************************
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

消息很清楚,但是我不太想知道如何解决。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您没有正确使用@MockBean

@MockBean将模拟内容注入您的AuditoryTest中,但您的DocumentServiceBackOffice一无所知。它仅知道已配置的bean rawRestTemplatejwtRestTemplate

此外,将其中一个标记为@Primary应该足以连接正确的一个。

答案 1 :(得分:0)

我已经解决了使用其他Configuration类的问题:

@TestConfiguration
public static class RestTemplateTestConfiguration {

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