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?
Update : As of Spring Boot 1.4.0 , TestRestTemplate
does not extend RestTemplate
anymore but still provides the same API as RestTemplate
.
TestRestTemplate
extends provides the same API as the RestTemplate
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);
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);
}));
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.