Search code examples
javaunit-testingjunitmockitojersey-client

how to mock sun jersey client post calls?


This is my code

@Service
public class PaymentHandler {
private static final Gson GSON = new Gson();

private static Client webServiceClient = createSslClient(); // function creates a ssl connection

public Response makePayment(String payload) {
    WebResource webResource = webServiceClient.resource(url);

    WebResource.Builder builder = webResource.getRequestBuilder();

    String r = builder
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(String.class, payload);

    Response response = GSON.fromJson(r, Response.class);
}
}

Here is how I try to test it which doesn't work , it always makes a call to the payment service. I am unable to mock it.

Client client = mock(Client.class );
WebResource webResource = mock(WebResource.class);
WebResource.Builder builder = mock(WebResource.Builder.class);
ClientResponse clientResponse = mock(ClientResponse.class);
when(client.resource(anyString())).thenReturn(webResource);
when(webResource.getRequestBuilder()).thenReturn(builder);

when(builder.type(anyString())).thenReturn(builder);
when(builder.accept(anyString())).thenReturn(builder);
when(builder.post(Matchers.eq(String.class), anyString())).thenReturn("Test");
paymentHandler.makePayment(payload); //assume that I send actual payload

Can someone please tell me how to mock this ?


Solution

  • Here is how I used mocked it

    @Mock
    Client client;
    
    @Mock
    WebResource webResource;
    
    @Mock
    WebResource.Builder builder;
    
    
    @Test
    public void test() {
    ReflectionTestUtils.setField(payeezyHandler,"webServiceClient",client);
    Mockito.when(client.resource(anyString())).thenReturn(webResource);
    Mockito.when(webResource.getRequestBuilder()).thenReturn(builder);
    
    Mockito.when(builder.type(MediaType.APPLICATION_JSON_TYPE)).thenReturn(builder);
    Mockito.when(builder.accept(MediaType.APPLICATION_JSON_TYPE)).thenReturn(builder);
    Mockito.when(builder.post(Matchers.eq(String.class),anyString())).thenReturn(fakeResponse());
    }
    

    I know that ReflectionTestUtils are bad to use. But if your test class has just one public function to test, then I guess there is no harm.