Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jersey/Mockito: NullInsteadOfMockException on client.post call verification

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?

like image 251
Joanna Derks Avatar asked Mar 06 '15 09:03

Joanna Derks


2 Answers

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.

like image 165
Dawood ibn Kareem Avatar answered Oct 21 '22 07:10

Dawood ibn Kareem


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.

like image 1
entpnerd Avatar answered Oct 21 '22 08:10

entpnerd