36

I am using TestRestTemplate for integration testing on our product.

I have one test that looks like this:

@Test
public void testDeviceQuery() {
    ResponseEntity<Page> deviceInfoPage = template.getForEntity(base, Page.class);

    // validation code here
}

This particular request expects a Header value. Can someone please let me know how I can add a header to the TestRestTemplate call?

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
DavidR
  • 6,622
  • 13
  • 56
  • 70

3 Answers3

46

Update: As of Spring Boot 1.4.0, TestRestTemplate does not extend RestTemplate anymore but still provides the same API as RestTemplate.

TestRestTemplate extends RestTemplate provides the same API as the RestTemplate, so you can use that same API for sending requests. For example:

HttpHeaders headers = new HttpHeaders();
headers.add("your_header", "its_value");
template.exchange(base, HttpMethod.GET, new HttpEntity<>(headers), Page.class);
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • 8
    This solved it, thanks a bunch. Just one part to note is that the `HttpHeaders` needs to be from the `org.springframework.http` package – Mr. Doomsbuster Jul 11 '17 at 22:51
29

If you want all of your requests using TestRestTemplate to include certain headers, you could add the following to your setup:

testRestTemplate.getRestTemplate().setInterceptors(
        Collections.singletonList((request, body, execution) -> {
            request.getHeaders()
                    .add("header-name", "value");
            return execution.execute(request, body);
        }));
DagR
  • 2,900
  • 3
  • 24
  • 36
2

If you want to use multiple headers for all your requests, you can add the below

 import org.apache.http.Header;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClients;
 import org.apache.http.message.BasicHeader;
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;


 private void setTestRestTemplateHeaders() {
    Header header = new BasicHeader("header", "value");
    Header header2 = new BasicHeader("header2", "value2");
    List<Header> headers = new ArrayList<Header>();
    headers.add(header);
    headers.add(header2);
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultHeaders(headers).build();
    testRestTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
 }

Once the headers are set you can either use TestRestTemplate [testRestTemplate] or RestTemplate [testRestTemplate.getRestTemplate()] for your REST calls

Vasu K S
  • 61
  • 3