因为JerseyTest必须扩展,所以我无法在Jersey的ResourceConfig中获得模拟资源。以下代码生成NullPointerException,因为还没有初始化mockResource:
@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"));
}
}
有人能看到这方面的方法吗?
答案 0 :(得分:4)
我通过将JerseyTest编写到测试类中而不是将其子类化来实现这一点。请参阅我的博文:http://datumedge.blogspot.co.uk/2012/08/mocking-rest-resources-with-jmock-and.html