[英]Add Header Value For Spring TestRestTemplate Integration Test
I am using TestRestTemplate
for integration testing on our product. 我正在使用
TestRestTemplate
对我们的产品进行集成测试。
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. 此特定请求需要Header值。 Can someone please let me know how I can add a header to the
TestRestTemplate
call? 有人可以告诉我如何在
TestRestTemplate
调用中添加标题吗?
Update : As of Spring Boot 1.4.0 , TestRestTemplate
does not extend RestTemplate
anymore but still provides the same API as RestTemplate
. 更新 : 从Spring Boot 1.4.0开始 ,
TestRestTemplate
不再扩展RestTemplate
,但仍然提供与RestTemplate
相同的API。
TestRestTemplate
extends provides the same API as the RestTemplate
扩展
RestTemplate
RestTemplate
, so you can use that same API for sending requests. 提供与
RestTemplate
相同的API,因此您可以使用相同的API来发送请求。 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
所有请求都包含某些标头,则可以将以下内容添加到您的设置中:
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 设置标头后,您可以使用
TestRestTemplate [testRestTemplate]
或RestTemplate [testRestTemplate.getRestTemplate()]
进行REST调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.