Issue
I have a service, which uses a RestTemplate
and for this it needs to get information from the Token.
public RoleKeycloak getRoleId(String idRole, String projectId) {
ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query, getHeaders()), String.class);
//more operations
}
I obtain the Headers information through a method getHeaders(), which uses a FeignClientInterceptor
, which is responsible for obtaining authorization from the header.
private HttpHeaders getHeaders() {
headers.set(ConstantsUtils.Authorization, FeignClientInterceptor.getBearerTokenHeader());
headers.set(ConstantsUtils.Content_Type, ConstantsUtils.GraphQL);
return headers;
}
@Component
public class FeignClientInterceptor implements RequestInterceptor {
public static final String getBearerTokenHeader() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(AUTHORIZATION_HEADER);
}
}
@Test
void createRoleTest() throws ParseException, IOException {
String response = "createRoleProject";
ResponseEntity<String> responseEntity = new ResponseEntity<String>(response, HttpStatus.ACCEPTED);
given(restTemplate.postForEntity("myurl", getHeaders(), String.class))
.willReturn(responseEntity);
RoleKeycloak roleKeycloak = roleServiceKeycloak.createRole("admin", "idProject");
assertNotNull(roleKeycloak);
}
I'm trying to test this method with jUnit
but I can't, not even with the information on the internet. I'm trying to mock FeignClientInterceptor
but I can't, always get a NullPointerException
in RequestContextHolder.getRequestAttributes();
Solution
Based on your comments & question, I am suggesting below solution:
Here, I am using mock static along with MockHttpServletRequest
where in test case you can create a MockHttpServletRequest & set one header.
Later on, using mockStatic, you can enable stubbing for execution of RequestContextHolder.getRequestAttributes()
.
@Test
void test() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(HttpHeaders.AUTHORIZATION, "SomeheaderValue");
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(attributes);
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
MockedStatic<RequestContextHolder> mockedStatic = mockStatic(RequestContextHolder.class);
mockedStatic.when(() -> RequestContextHolder.getRequestAttributes()).thenReturn(requestAttributes);
System.out.println(FeignClientInterceptor.getBearerTokenHeader()); // this will print "SomeheaderValue"
}
You need to use below dependency to support mock static:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
You can then directly call FeignClientInterceptor.getBearerTokenHeader()
from getHeaders
method in unit test.
Answered By - Ashish Patil
Answer Checked By - Pedro (JavaFixing Volunteer)