Весенний загрузочный интеграционный тест. Не удалось передать значения заголовка из класса SprinBootTest в Interceptor
Мне нужно установить заголовки http в классе SprinBootTest и получить эти заголовки http в классе перехватчика. Но заголовки, установленные в классе SprinBootTest, не передаются перехватчику и не получают нулевое значение от перехватчика.
Мой код:
// Spring boot test class
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private MockMvc mockMvc;
private static HttpHeaders headers = null;
@Before
public void initalise() {
headers = new HttpHeaders();
headers.set("auth", "auth value");
}
@Test
public void testGetAccounts() {
ResponseEntity<Object> response = restTemplate.exchange(
"http://localhost:8080/enquiry/accounts", HttpMethod.GET, new
HttpEntity<>(null, headers), Object.class);
System.out.println("Response is: "+response);
}
}
// Interceptor
@Component
public class DemoRequestInterceptor implements ClientHttpRequestInterceptor {
@Autowired
private HttpServletRequest httpServletRequest;
@Override
public ClientHttpResponse intercept(final HttpRequest httpRestRequest, final byte[] body, final ClientHttpRequestExecution execution) throws IOException {
final HttpHeaders headers = httpRestRequest.getHeaders();
// Below statement prints as null. But It should print as "auth value".
// Also I could not found the header value (that set in above program)
// from above statement "final HttpHeaders headers =
// httpRestRequest.getHeaders()"
System.out.println(httpServletRequest.getHeader("auth"));
final ClientHttpResponse response = execution.execute(httpRestRequest, body);
return response;
}
private void addHeaders(final HttpRequest httpRestRequest){
final HttpHeaders headers = httpRestRequest.getHeaders();
headers.add(ControllerConstants.AUTHORISATION, httpServletRequest.getHeader(ControllerConstants.AUTHORISATION));
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
}
}