Reputation: 91
This is the sample code of what I have written
String bearerToken="Bearer "+ token;
HttpClient client = HttpClientBuilder.create().build();
request.addHeader("Authorization",bearerToken);
request.addHeader("cache-control", "no-cache");
HttpResponse response=client.execute(request);
System.out.println("Response Code:" + response.getStatusLine().getStatusCode());
How can I mock these request headers in java? How do I mock Authorization and response?.
Upvotes: 0
Views: 5812
Reputation: 628
In your unit test class you need to mock client:
@Mock
private HttpClient client;
Then you tell mockito in @Before method to actually create your mocks by
MockitoAnnotations.initMocks(YourTestClass);
Then in your test method, you can mock what execute() method should return:
Mockito.when(client.execute(any()/* or wahtever you want here */)).thenReturn(your json object);
Mocking your HttpClient is preferred more because there may be some times when if you make an actual call to the rest API after mocking your headers the API may return unwanted response[when the service is down or restarting].
But if you still want to mock a private field you can do it using
ReflectionUtils.setField()
Upvotes: 2