views:

998

answers:

2

I have a JAX-RS web service implemented with Restlet library and now I want to test it. In order to do that I'd like to host this service in my test by preinitializing it with mocked services.

What is the best way to host such a service and execute the test calls?

@Path("/srv")
public class MyService
{
   @GET
   public void action(@Context UriInfo uri)
   { ... }
}

@Test
public void myTest()
{
   MyService service = new MyService();
   service.setSomething(...);

   // How do I host it?

   // How do I call it?
}
A: 

Restlet lets you run your web services on various server "connectors", and it is quite easy to switch from one server to another. We normally run our web services on a Sun Glassfish Java EE application server cluster, but for testing them we use a connector that links with the Simple HTTP Server to run the web services as a standalone application. There also are server connectors for AsyncWeb, Jetty, Grizzly, and an internal HTTP server.

On the client side, you should consider the Restlet client library. It's pretty concise and it's designed to mesh well with Restlet servers. We use the Apache HTTP Client connector.

For testing, we've created the Fetcher class. This is implemented using the Restlet client API. To use it, you pretty much call the fetch() method:

DTO person = fetch("/employee/1234");
DTO department = fetch("/department/" + person.getDepartment());

Fetch() tacks the given resource name onto the base URI of the web services (say "http://localhost:8182"), uses the Restlet client API to fetch an XML representation, then deserializes the fetched XML into a data transfer object (a POJO).

You can see that this really makes unit testing quite easy. Before the unit tests, you fire up the web services on a standalone server like Simple or Jetty. During the unit tests you fetch DTOs, DOM trees, json.org objects or whatever using Fetcher, then apply test assertions to to what was returned. If you need to test at a more detailed level, you can use the Restlet client code directly.

Jim Ferrans
The whole point of my question was to figure out how to initialize a web service/component INSIDE the process. I don't want/can't run it on a remote server. There is a need to initialize the service with mocked instances BEFORE it's exposed as a web service. Is there a way to expose an INSTANCE of a class/component as a service?
IgorM
any answers? IgorM - have you worked it out?
Vatsala
+1  A: 

@see http://www.restlet.org/documentation/1.1/firstSteps#part04

You should be able to run the Restlet service in embedded way and use apache HttpClient to call methods. I've done it and it quite simple.

amertum