java - 将 JMock 资源与 Jersey 测试框架结合使用

标签 java jersey jmock

因为 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/

相关文章:

java - JMock- java.lang.NoSuchMethodError : org. hamcrest.Matcher.describeMismatch() 错误

java - 从 JMock 的对象返回 ImmutableSet 导致 UndeclaredThrowableException

java - 回调中的 Threadlocal 使用

jakarta-ee - Jersey:在不使用 web.xml 文件的情况下禁用 OPTIONS 请求的自动 Wadl 生成?

java - 为复杂对象生成 JSON 消息

java - 如何使用 JAX-RS 流式传输无休止的 InputStream

java - 使用 Jmockit 模拟公共(public)方法

java - 什么时候在 stringbuilder/stringbuffer 上使用 string?

java - 我想从我的服务启动线程,这样操作就不会在 android 的主线程中运行

java - 如何中止正在运行的 JDBC 事务?