Reputation:
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,
Upvotes: 0
Views: 2623
Reputation: 95634
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);
Upvotes: 1