Question

I am having some problems with mocking com.sun.jersey.api.client.ClientResponse but only when I am setting the .type(MediaType.MULTIPART_FORM_DATA_TYPE.

I am stuck with jersey-client 1.18.

Here is the code under test:

 ClientResponse clientResponse = client.resource(url)
            .accept("application/json")
            .entity(multiPart)
            .type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .post(ClientResponse.class);

Here is the mocking for the test:

 when(clientResponse.getEntity(String.class)).thenReturn(body);
 when(builder.post(eq(ClientResponse.class))).thenReturn(clientResponse);
 when(builder.type(MediaType.MULTIPART_FORM_DATA_TYPE)).thenReturn(builder);
 when(webResource.accept(anyString())).thenReturn(builder);
 when(client.resource(anyString())).thenReturn(webResource);;

The error I receive is a NullPointerException in the Code under Test at the line:

 .type(MediaType.MULTIPART_FORM_DATA_TYPE)

Anyone know how to mock the Client.resource().type()?

Was it helpful?

Solution

If I understand what you're doing, you've mocked a builder.

You don't have mocking that covers calling builder.entity() on the builder returned by webResource.accept(), so it returns null and the next call in the chain fails (builder.type()).

Add:

 when(builder.entity(anyString())).thenReturn(builder);

(provided multiPart is a String)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top