I've run into a strange issue with unit testing the following jersey client call:
WebResource webResource = _client.resource(url);
ClientResponse response = webResource
.accept("application/json")
.type("application/x-www-form-urlencoded")
.post(ClientResponse.class, postBody);
PostBody is a MultivaluedMap.
The unit test verifies fine the accept and type calls but fails on the post one with this exception:
org.mockito.exceptions.misusing.NullInsteadOfMockException:
Argument passed to verify() should be a mock but is null!
Here's the test code:
_client = Mockito.mock(Client.class);
_webResource = Mockito.mock(WebResource.class);
_builder = Mockito.mock(WebResource.Builder.class);
_response = Mockito.mock(ClientResponse.class);
Mockito.when(_client.resource(Mockito.anyString())).thenReturn(_webResource);
Mockito.when(_response.getEntity(Mockito.any(Class.class))).thenReturn(new RefreshTokenDto());
Mockito.when(_response.getStatus()).thenReturn(200);
Mockito.when(_builder.post(Mockito.eq(ClientResponse.class), Mockito.anyObject())).thenReturn(_response);
Mockito.when(_builder.type(Mockito.anyString())).thenReturn(_builder);
Mockito.when(_webResource.accept(Mockito.anyString())).thenReturn(_builder);
RefreshTokenDto response = _clientWrapper.exchangeAuthorizationCodeForToken(_token);
Assert.assertNotNull(response);
Mockito.verify(_client.resource(_baseUrl + "token"));
Mockito.verify(_webResource.accept("application/json"));
Mockito.verify(_builder.type("application/x-www-form-urlencoded"));
// TODO: this line throws NullRefExc for some unknown reason
Mockito.verify(_builder.post(Mockito.any(Class.class), Mockito.any(MultivaluedMap.class)));
Can you see anything wrong with this code?
Yes. You've misused verify. The argument to verify has to be the mock itself. Then you call the method you want to verify on the value that's returned by verify. So in this case, the first verify call should be
Mockito.verify(_client).resource(_baseUrl + "token");
and similarly for the other verify calls.
I ran into this issue, but for when() instead of verify(). I found this question by googling. For me, I had forgotten to add MockitoAnnotations.initMocks() in my test class' constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With