Search code examples
javaspringunit-testingtestingresttemplate

Test RestTemplate Interceptors


i've implemented a Interceptors for RestTemplate (RestTemplateInterceptor.class):

@Autowired
private RestConfigurations configurations;

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.additionalInterceptors((ClientHttpRequestInterceptor) (httpRequest, bytes, clientHttpRequestExecution) -> {
        HttpHeaders headers = httpRequest.getHeaders();
        headers.add("X-API-KEY", configurations.getApiKey());

        return clientHttpRequestExecution.execute(httpRequest,bytes);
    }).build();
}

Now I want to test it. :) One try looks like that:

@ExtendWith(SpringExtension.class)
@RestClientTest({RestTemplateInterceptor.class, RestConfigurations.class})
@AutoConfigureMockMvc
@SpringBootTest
class MyTestClass {
public static final String URL = "http://testMe.com/";

@Autowired
MockRestServiceServer mockServer;

@Autowired
RestTemplateBuilder restTemplateBuilder;

@Test
@DisplayName("Should include header X-API-KEY")
void headerShouldContainsXApiKey() throws Exception {
    mockServer.expect(requestTo(URL)).andRespond(withSuccess("Hello world", TEXT_PLAIN));

    String body = restTemplateBuilder.build().exchange(URL//
            , GET, //
            null,  //
            String.class).getBody();
    assertThat(body).isEqualTo("Hello world");

    mockServer.expect(header("X-API-KEY", ""));
}

But i failed with:

java.lang.AssertionError: No further requests expected: HTTP GET http://test.hornbach.de/ 0 request(s) executed.

Anyone a hint? Thanks


Solution

  • If you check the Javadoc, you'll see that when you call additionalInterceptors, you're not modifying the existing builder instance but instead getting a new builder with a slightly different configuration. When you then call restTemplateBuilder.build() in your test case, you're building a template that has the unmodified configuration.

    The ideal way to test something like this is to do so directly on the interceptor instance itself, but if you're wanting to perform a functional test by calling through to a mock server, you should inject the completed RestTemplate instance into your test case.