users@jersey.java.net

Re: [Jersey] How to Use Mocks With Jersey Test Framework?

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Wed, 27 Jan 2010 12:08:00 +0100

Hi John,

I recently replied to another user on this topic:

http://markmail.org/search/?q=list
%3Anet.java.dev.jersey.users#query:list%3Anet.java.dev.jersey.users
+page:1+mid:xp4auohvqb3xn7mr+state:results

Although it is related to Spring i think the same approach applies and
that an IoCComponentProvider factory needs to be registered that is
responsible for instantiating the mocked instances.

I can provide more details on this respect if required.

Paul.

On Jan 26, 2010, at 4:38 PM, JohnM_Gallagher_at_timeinc.com wrote:

> 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.