سؤال

Because JerseyTest has to be extended, I've been unable to get a mock resource into Jersey's ResourceConfig. The following code generates a NullPointerException because mockResource has yet to be initialised:

@Path("/")
public interface MyResource {
    @GET String get();
}

public class MockResourceTest extends JerseyTest {
    @Rule public JUnitRuleMockery context = new JUnitRuleMockery();
    private MyResource mockResource = context.mock(MyResource.class);

    @Override
    protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
        return new GrizzlyTestContainerFactory();
    }

    @Override
    protected AppDescriptor configure() {
        DefaultResourceConfig resourceConfig = new DefaultResourceConfig();
        // FIXME: configure() is called from superclass constructor, so mockResource is still null!
        resourceConfig.getSingletons().add(mockResource);
        return new LowLevelAppDescriptor.Builder(resourceConfig).build();
    }

    @Test
    public void respondsToGetRequest() {
        context.checking(new Expectations() {{
            allowing(mockResource).get(); will(returnValue("foo"));
        }});

        String actualResponse = client().resource("http://localhost:9998/").get(String.class);
        assertThat(actualResponse, is("foo"));
    }
}

Can anyone see a way round this?

هل كانت مفيدة؟

المحلول

I've got this working by composing JerseyTest into the test class, rather than subclassing it. See my blog post: http://datumedge.blogspot.co.uk/2012/08/mocking-rest-resources-with-jmock-and.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top