2

因为 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"));
    }
}

任何人都可以看到解决这个问题的方法吗?

4

1 回答 1

4

我通过将 JerseyTest 组合到测试类而不是对其进行子类化来完成这项工作。请参阅我的博客文章:http ://datumedge.blogspot.co.uk/2012/08/mocking-rest-resources-with-jmock-and.html

于 2012-08-01T18:28:13.447 回答