0

I am using Mockito to mock Jersey Client API. I have a mock Response which returns me a nullPointerException.

This is what I have done so far

when(invocationBuilder.post(Entity.entity(anyString(),MediaType.APPLICATION_XML))).thenReturn(response);

Is there anyway to fix this. Thanks,

  • Please post how you initialize your Mock object. We don't have enough information to help you now. – Guillaume F. Dec 02 '15 at 20:32
  • Hope this helps clientConfig = mock(ClientConfiguration.class); client = mock(Client.class); clientConfig.createClient(); webTarget = mock(WebTarget.class); clientConfig.createWebResource(URI); response = mock(Response.class); invocationBuilder = mock(Invocation.Builder.class); statusType = mock(StatusType.class); –  Dec 02 '15 at 20:34

1 Answers1

1

You can't use Mockito matchers like that: They can only be used in the top level (here, as arguments to post). Furthermore, when you use one matcher, you have to use matchers for all arguments. I've written more about matchers here.

Matchers like anyString actually return null, and your NullPointerException likely comes from Entity.entity failing to accept a null value. (When you use matchers correctly in a when or verify statement, Mockito intercepts the call anyway, so the null doesn't interfere with anything.)

Instead, you'll need to return the response for everything and later use an ArgumentCaptor to later ensure that the MediaType is APPLICATION_XML:

when(invocationBuilder.post(any())).thenReturn(response);
/* ... */
ArgumentCaptor<Entity> captor = ArgumentCaptor.forClass(Entity.class);
verify(invocation).post(captor.capture());
assertEquals(APPLICATION_XML, captor.getValue().getMediaType());

Or use a custom ArgumentMatcher<Entity> to match:

ArgumentMatcher<Entity> isAnXmlEntity = new ArgumentMatcher<Entity>() {
  @Override public boolean matches(Object object) {
    if (!(entity instanceof Entity)) {
      return false;
    }
    Entity entity = (Entity) object;
    return entity.getMediaType() == APPLICATION_XML;
  }
};
when(invocationBuilder.post(argThat(isAnXmlEntity)).thenReturn(response);
Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251