Testing Jersey Based REST Services with Grizzly

Posted on Monday, March 7, 2011


In my last post, we had seen how easy it was to create REST based services with Spring and Jersey. In this post we would quickly see how we can unit test them. Ok, this is not entirely a unit test in the strict sense because we are not testing the resource in isolation but it is a good strategy nevertheless because it helps us to test the resource right from the IDE.

For this, we would include the Grizzly servlet webserver dependency in our pom.xml.


Once we have the Grizzly server, we would have to power it up at the start of our tests so that the resource can execute inside the container. The test start-up would look like this

	public void setUp() throws Exception {
		threadSelector = GrizzlyMain.startServer();
		ClientConfig clientConfiguration = new DefaultClientConfig();
		Client client = Client.create(clientConfiguration);
		webresource = client.resource(GrizzlyMain.baseUri);

Also, at the end of every test, we have to terminate the endpoint so that the port is now available for the next test. Hence, we do

	public void tearDown() throws Exception {

If you would notice, we have started the GrizzlyServer with GrizzlyMain.startServer(); Let us see what this class looks like

public class GrizzlyMain {

    private static int getPort(int defaultPort) {
        String port = System.getenv("JERSEY_HTTP_PORT");
        if (null != port) {
            try {
                return Integer.parseInt(port);
            } catch (NumberFormatException e) {
        return defaultPort;

    final static URI baseUri = UriBuilder.fromUri( "http://localhost/" ).port( 9998 ).build();

    public static SelectorThread startServer() throws IOException{
    	final ServletAdapter adapter =new ServletAdapter();
    	adapter.addInitParameter( "com.sun.jersey.config.property.packages", "com.inphina.sample" );
    	adapter.addInitParameter( "com.sun.jersey.api.json.POJOMappingFeature", "true" );
    	adapter.addContextParameter( "contextConfigLocation","classpath:applicationContext.xml"  );
    	adapter.addServletListener( "org.springframework.web.context.ContextLoaderListener" );
    	adapter.setServletInstance( new SpringServlet() );
    	adapter.setProperty( "load-on-startup", 1 );

    	System.out.println("********" + baseUri.getPath());
        SelectorThread threadSelector = GrizzlyServerFactory.create(baseUri, adapter);
        return threadSelector;

    public static void main(String[] args) throws IOException {
        System.out.println("Starting grizzly...");
        SelectorThread threadSelector = startServer();
                "Jersey app started with WADL available at %sapplication.wadl\n" +
                "Hit enter to stop it...", baseUri));

As you would notice, the startServer() method, starts the server along with all the details which are present in our web.xml (refer to the last post). Here, we register the SpringServlet and also pass all the init parameters to the servlet. A snapshot of the web.xml is shown here


Now, let us look at a sample test

	public void getOnHelloWorldPath() {
		// get the initial representation
		String s = webresource.path("helloworld").accept("application/json").get(String.class);
		Assert.assertEquals("{\"name\":\"Vikas Hazrati\",\"age\":36,\"email\":\"vhazrati@inphina.com\"}", s);

Here, we make a GET call at the path helloworld and expect a JSON string to be returned which should be equal to what we are expecting. Likewise to make a sample post call you would have a method like this

	public void testPostLoginJSONFormat() {
		User user = new User();
		Address address = new Address();


Hence, it is easy to test the REST services with the lightweight Grizzly server in place. The complete code for this and previous post can be accessed here.

Posted in: Architecture, Java