2

I have changed a Spring Boot (2.1.4) service that consumes a RestTemplate to use a @Qualifier. Now my Test (with @RestClientTest and @AutoConfigureWebClient) fails because it can not resolve the bean.

How do I fix this?

The config:

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

The service:

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

The test:

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

  @Autowired
  private CastorClient cut;

  @Autowired
  private MockRestServiceServer server;

The error:

[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)}
Martin Schröder
  • 4,176
  • 7
  • 47
  • 81

2 Answers2

5

You should not use (registerRestTemplate = true) as it will create a RestTemplate bean for you which is not the one you use.

If your qualified RestTemplate bean is declared in your CastorConfiguration, try using @Import(CastorConfiguration.class)

HTN
  • 3,388
  • 1
  • 8
  • 18
  • Nope. The config class is `RestTemplateConfig` and simply importing that doesn't help. How would I declare my own `RestTemplate` for use with `@RestClientTest`? I already have `@TestConfiguration` class in the test class. – Martin Schröder Apr 16 '19 at 13:25
2

Solution that worked for me: @AutoConfigureWebClient (without (registerRestTemplate = true)). In the @TestConfiguration class create a bean of RestTemplate with the right @Qualifier

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

Inject that into the test class

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

Now we need to wire that into the MockRestServiceServer. We do that via @BeforeEach

private MockRestServiceServer server;
@BeforeEach
  void setUp () {
    server = MockRestServiceServer.bindTo(restTemplate).build();
  }
Martin Schröder
  • 4,176
  • 7
  • 47
  • 81