因为 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"));
}
}
有人能找到解决这个问题的方法吗?
最佳答案
我通过将 JerseyTest 组合到测试类中而不是子类化它来实现此目的。请参阅我的博文:http://datumedge.blogspot.co.uk/2012/08/mocking-rest-resources-with-jmock-and.html
关于java - 将 JMock 资源与 Jersey 测试框架结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11749520/