因为必须扩展JerseyTest,所以我无法将模拟资源获取到Jersey的ResourceConfig中。以下代码生成NullPointerException,因为尚未初始化嘲笑资源:
@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"));
}
}
谁能看到解决这个问题的方法?
最佳答案
我通过将JerseyTest组合到测试类中而不是将其子类化来完成此工作。请参阅我的博客文章:http://datumedge.blogspot.co.uk/2012/08/mocking-rest-resources-with-jmock-and.html