Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Jersey REST client to throw HTTP 500 responses?

I am writing a Java class that uses Jersey under the hood to send an HTTP request to a RESTful API (3rd party).

I would also like to write a JUnit test that mocks the API sending back HTTP 500 responses. Being new to Jersey, it is tough for me to see what I have to do to mock these HTTP 500 responses.

So far here is my best attempt:

// The main class-under-test
public class MyJerseyAdaptor {
    public void send() {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        String uri = UriBuilder.fromUri("http://example.com/whatever").build();
        WebResource service = client.resource(uri);

        // I *believe* this is where Jersey actually makes the API call...
        service.path("rest").path("somePath")
                .accept(MediaType.TEXT_HTML).get(String.class);
    }
}

@Test
public void sendThrowsOnHttp500() {
    // GIVEN
    MyJerseyAdaptor adaptor = new MyJerseyAdaptor();

    // WHEN
    try {
        adaptor.send();

        // THEN - we should never get here since we have mocked the server to
        // return an HTTP 500
        org.junit.Assert.fail();
    }
    catch(RuntimeException rte) {
        ;
    }
}

I am familiar with Mockito but have no preference in mocking library. Basically if someone could just tell me which classes/methods need to be mocked to throw a HTTP 500 response I can figure out how to actually implement the mocks.

like image 732
IAmYourFaja Avatar asked Dec 24 '12 01:12

IAmYourFaja


1 Answers

Try this:

WebResource service = client.resource(uri);

WebResource serviceSpy = Mockito.spy(service);

Mockito.doThrow(new RuntimeException("500!")).when(serviceSpy).get(Mockito.any(String.class));

serviceSpy.path("rest").path("somePath")
            .accept(MediaType.TEXT_HTML).get(String.class);

I don't know jersey, but from my understanding, I think the actual call is done when get() method is invoked. So you can just use a real WebResource object and replace the behavior of the get(String) method to throw the exception instead of actually execute the http call.

like image 129
Luigi R. Viggiano Avatar answered Sep 22 '22 18:09

Luigi R. Viggiano