2

JerseyTest を拡張する必要があるため、Jersey の ResourceConfig にモック リソースを取得できませんでした。次のコードは、mockResource がまだ初期化されていないため、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"));
    }
}

誰でもこれを回避する方法を見ることができますか?

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 に答える