How to mock a Jersey REST client to send HTTP 500 responses?

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

I would also like to write a JUnit test that makes fun of the API sending HTTP 500 responses. As a newcomer to Jersey, I have a hard time understanding what I need to do to mock these HTTP 500 responses.

So far this 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 the mocking library. Basically, if someone can just tell me which classes / methods need to be mocked to throw an HTTP 500 response, I can figure out how to actually implement the layouts.

+4
source share
2 answers

Try the following:

 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 do not know knitwear, but from my understanding, I think that the actual call is made when the get () method is called. That way, you can simply use the real WebResource object and replace the get(String) method to throw an exception instead of actually making an HTTP call.

+4
source

I am writing a web application in Jersey ... and we are sending WebApplicationException error responses for HTTP. You can simply pass the response code as a constructor parameter. For instance,

 throw new WebApplicationException(500); 

When this exception is thrown to the server, it appears in my browser as a response of the 500 HTTP response.

Not sure if this is what you want ... but I thought that input might help! Good luck.

+1
source

All Articles