users@jersey.java.net

How to Use Mocks With Jersey Test Framework?

From: <JohnM_Gallagher_at_timeinc.com>
Date: Tue, 26 Jan 2010 10:38:53 -0500

I am using Jersey in a project that I am working on. I try to use
test-driven development techniques whenever possible, and I was
wondering how I could use a mocking framework, such as JMock or
EasyMock, with the Jersey test framework. My Jersey class looks like
this:

 

@Path("/helloworld")

public class HelloWorldResource {

     

    private CustomerService customerService; //I would like to mock this

 

    @GET

    @Produces("text/plain")

    public String getMessage() {

         //business functionality

    }

            

    public void setCustomerService(final CustomerService cs) {

        customerService = cs;

    }

}

 

I would like to mock the CustomerService member. I have looked at the
Jersey test framework api, but it seems that there is now easy way to do
this, because to construct an instance of JerseyTest you need to provide
a package name or a reference to the class object of the Jersey class
under test. What I would like to do (in pseudo-code) is something like
this:

 

import org.junit.Assert;

import org.junit.Test;

 

import com.sun.jersey.api.client.WebResource;

import com.sun.jersey.test.framework.JerseyTest;

import com.sun.jersey.test.framework.LowLevelAppDescriptor;

import com.sun.jersey.test.framework.spi.container.TestContainerFactory;

import
com.sun.jersey.test.framework.spi.container.http.HTTPContainerFactory;

import org.jmock.integration.junit4.JUnit4Mockery;

 

public class HelloWorldResourceTest extends JerseyTest {

 

    @Override

    protected TestContainerFactory getTestContainerFactory() {

        return new HTTPContainerFactory();

    }

 

    public HelloWorldResourceTest() {

            HelloWorldResource hw = new HelloWorldResource();

            CustomerService csMock = mock(CustomerService);

            hw.setCustomerService(csMock);

            super(new LowLevelAppDescriptor.Builder(csMock).build());

    }

 

    @Test

    public void testGet() {

        WebResource r = resource().path("helloworld");

 

        //assertions, etc

    }

}

 

How could I do this with Jersey? Is it even possible? Thanks for your
help.