Spring boot testing of a rest client using @RestClientTest

Viewed 7853

I am using spring boot 1.5.8 and want to test my client:

@Component
public class RestClientBean implements RestClient {
  private Map<String, RestTemplate> restTemplates = new HashMap<>();

  @Autowired
  public RestClientBean(RestTemplateBuilder builder, SomeConfig conf) {
    restTemplates.put("first", builder.rootUri("first").build();
    restTemplates.put("second", builder.rootUri("second").build();
  }
}

with the following test:

@RunWith(SpringRunner.class)
@RestClientTest(RestClient.class)
public class RestClientTest {
  @Autowired
  private RestClient client;

  @Autowired
  private MockRestServiceServer server;

  @TestConfiguration
  static class SomeConfigFooBarBuzz {
    @Bean
    public SomeConfig provideConfig() {
        return new SomeConfig(); // btw. not sure why this works, 
                                 // but this is the only way 
                                 // I got rid of the "unable to load 
                                 // SomeConfig auto-wire" or something like this :)
                                 // Anyway not my main issue
                                 // EDIT: just realized that the whole 
                                 // @TestConfiguration part can be avoided by
                                 // adding SomeConfig.class to the classes in the
                                 // @RestClientTest annotation
    }
  }

  @Before
  public void setUp() throws Exception {
    server.expect(requestTo("/somePath")) // here an exception is thrown
                                          // (main issue)
          .andRespond(withSuccess("<valid json>", MediaType.APPLICATION_JSON));
  }
}

The exception is very clear:

java.lang.IllegalStateException: Unable to use auto-configured 
MockRestServiceServer since MockServerRestTemplateCustomizer has been bound to 
more than one RestTemplate

But is it somehow possible to get this tested or is it not allowed to instantiate two different rest templates in one client class? I have just the need to use the first rest template in some cases and the second one in some others.

1 Answers
Related