I am trying to unit test a Spring bean I implemented, but come across a difficulty here. This bean is to call a distant REST service on certain occasions.
However, in my tests, I would like it to call a mock servlet inside my test context, not a distant server.
The call is made using Apache’s httpclient library, the URL is set in the applicationContext (so I can provide any fake URI to the bean when testing). The service should return a stream.
The call looks like the following:
HttpClient client = new DefaultHttpClient();
URIBuilder builder = new URIBuilder(theURIProvidedInContext);
// set parameters on builder
URI uri = builder.build();
HttpGet get = new HttpGet(uri);
HttpEntity entity = client.execute(get).getEntity();
return entity.getContent();
I searched Google all morning but only found how to unit-test servlets. Can anybody give some insight here?
You’re not going to be able to call a mock servlet in a test context because there’s no application server. Instead, you can pull out that code that uses HTTP Client to make the call into a separate bean, and then mock that to return the desired stream.
If it’s a REST service, you can create a JAX-RS annotated class as a test double (I won’t call it a mock), and start it with an embedded server like Grizzly or Jersey. That will start up an HTTP server for you. Your annotated class can throw 404, 500, etc. depending on how you want the test to proceed. See JAX-RS with embedded server