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

Spring: How to combine @RestClientTest with a RestTemplate with @Qualifier?

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

我该如何解决这个问题?

配置:

  @Bean
  @Qualifier("eureka")
  @LoadBalanced
  RestTemplate eurekaRestTemplate() {

服务:

  public ClarkClient(
      @Qualifier("eureka") RestTemplate restTemplate, ClarkConfiguration configuration)
      throws URISyntaxException {

测试:

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

  @Autowired
  private CastorClient cut;

  @Autowired
  private MockRestServiceServer server;

错误:

[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)}

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

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

对我有用的解决方案:@AutoConfigureWebClient(没有 (registerRestTemplate = true))。 在 @TestConfiguration class 中创建一个 RestTemplate 的 bean 与右边的 @Qualifier

@Bean
@Qualifier("eureka")
public RestTemplate eurekaRestTemplate() {
  return new RestTemplate();
}

将其注入测试 class

@Autowired
@Qualifier("eureka")
private RestTemplate restTemplate;

现在我们需要将其连接到 MockRestServiceServer。我们通过 @BeforeEach

private MockRestServiceServer server;
@BeforeEach
  void setUp () {
    server = MockRestServiceServer.bindTo(restTemplate).build();
  }