Jersey / Mockito: NullInsteadOfMockException while checking client client.post

I had a strange problem with unit testing the following 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 multi-valued card.

unit test checks the subtle calls accept and type , but the post fails 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))); 

Do you see something wrong with this code?

+5
source share
1 answer

Yes. You have used verify . The verify argument must be the layout itself. Then you call the method you want to check on the value returned by verify . Therefore, in this case, the first call to verify should be

 Mockito.verify(_client).resource(_baseUrl + "token"); 

and similarly for other verify calls.

+9
source

Source: https://habr.com/ru/post/1214802/


All Articles