Using JMock resources with Jersey Test Framework
Question
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?
La solution
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow