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?
TestRestTemplate is not an extension of RestTemplate, but rather an alternative that simplifies integration testing and facilitates authentication during tests. It helps in customization of Apache HTTP client, but also it can be used as a wrapper of RestTemplate.
In order to configure your TestRestTemplate, the official documentation suggests you to use the TestRestTemplate, as shown in the example below (for example, to add a Basic Authentication): public class YourEndpointClassTest { private static final Logger logger = LoggerFactory. getLogger(YourEndpointClassTest.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With