Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Header Value For Spring TestRestTemplate Integration Test

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?

like image 354
DavidR Avatar asked Jan 06 '16 19:01

DavidR


People also ask

What is the difference between TestRestTemplate and RestTemplate?

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.

How do you initialize TestRestTemplate?

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.


2 Answers

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); 
like image 140
Ali Dehghani Avatar answered Oct 17 '22 08:10

Ali Dehghani


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);         })); 
like image 31
DagR Avatar answered Oct 17 '22 10:10

DagR