Spring:如何将 @RestClientTest 与带有 @Qualifier 的 RestTemplate 结合起来?

Rei*_*der 2 java spring qualifiers spring-boot spring-boot-test

我已经更改了 Spring Boot (2.1.4) 服务,该服务消耗 aRestTemplate以使用@Qualifier. 现在我的测试(使用@RestClientTest@AutoConfigureWebClient)失败了,因为它无法解析 bean。

我该如何解决?

配置:

  @Bean
  @Qualifier("eureka")
  @LoadBalanced
  RestTemplate eurekaRestTemplate() {
Run Code Online (Sandbox Code Playgroud)

服务:

  public ClarkClient(
      @Qualifier("eureka") RestTemplate restTemplate, ClarkConfiguration configuration)
      throws URISyntaxException {
Run Code Online (Sandbox Code Playgroud)

考试:

@ExtendWith({SpringExtension.class, MockitoExtension.class})
@RestClientTest({CastorClient.class, CastorConfiguration.class})
@AutoConfigureWebClient(registerRestTemplate = true)
class CastorClientWebTest {

  @Autowired
  private CastorClient cut;

  @Autowired
  private MockRestServiceServer server;
Run Code Online (Sandbox Code Playgroud)

错误:

[2019-04-16T14:02:22,614] [WARN ] [            ....AnnotationConfigApplicationContext] [refresh 557] : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'castorClient' defined in file [/home/martinsc/java/routing/route-testing-batch-manager/out/production/classes/com/tyntec/routetesting/batchmanager/core/clients/CastorClient.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=eureka)}
Run Code Online (Sandbox Code Playgroud)

HTN*_*HTN 5

您不应该使用它(registerRestTemplate = true),因为它会为您创建一个不是您使用的 RestTemplate bean。

如果您的 中声明了合格的 RestTemplate bean CastorConfiguration,请尝试使用@Import(CastorConfiguration.class)