VishnuVS
VishnuVS

Reputation: 1146

Is there a way to get the bearerToken set in HttpHeaders to perform validation in test?

I have a method that builds HttpHeaders. It fetches a bearerToken after logging in and sets it in the header. I would like to verify that the token is being set in a unit test, but I am unable to find any method to get the token from the header.

This is the method that builds the headers:

public static HttpHeaders buildHeaders() {
    HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    String bearerToken = getToken();
    headers.setBearerAuth(bearerToken);

    return headers;
}

And this is my test:

    @Test
void shouldBuildHeaders() {
    HttpHeaders httpHeaders = Util.buildHeaders();
    assertNotNull(httpHeaders);
    assertEquals(httpHeaders.getAccept(), Collections.singletonList(MediaType.APPLICATION_JSON));

    //I would like to do something like this to verify if the token is being set.
    // String bearerToken = httpHeaders.getBearerToken();
    // assertNotNull(bearerToken);
}

Is there any way to get the token, or is there anything wrong in the way I am testing?

Upvotes: 0

Views: 383

Answers (1)

Diogo Sarmento
Diogo Sarmento

Reputation: 19

You can try to loop trough your headers to see the keys that are available, like this:

httpHeaders.forEach((key,value)->{
    System.out.println(key+"-->"+value);
});

This allows you to check on all the headers that you have.

However in you case you can just look up the specific header that you want, by looking at the documentation bellow (I'm assuming you are using Spring): https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBearerAuth-java.lang.String-

The header key is actually "Authorization", meaning that you can access it's value by using the code bellow:

String bearerToken = httpHeaders.getFirst(HttpHeaders.AUTHORIZATION);

Upvotes: 1

Related Questions