如何模拟 Jersey REST 客户端以抛出 HTTP 500 响应?

IAm*_*aja 5 java rest jersey mockito

我正在编写一个 Java 类,它在底层使用Jersey将 HTTP 请求发送到 RESTful API(第 3 方)。

我还想编写一个 JUnit 测试来模拟 API 发送回 HTTP 500 响应。作为泽西岛的新手,我很难知道我必须做些什么来模拟这些 HTTP 500 响应。

到目前为止,这是我最好的尝试:

// The main class-under-test
public class MyJerseyAdaptor {
    public void send() {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        String uri = UriBuilder.fromUri("http://example.com/whatever").build();
        WebResource service = client.resource(uri);

        // I *believe* this is where Jersey actually makes the API call...
        service.path("rest").path("somePath")
                .accept(MediaType.TEXT_HTML).get(String.class);
    }
}

@Test
public void sendThrowsOnHttp500() {
    // GIVEN
    MyJerseyAdaptor adaptor = new MyJerseyAdaptor();

    // WHEN
    try {
        adaptor.send();

        // THEN - we should never get here since we have mocked the server to
        // return an HTTP 500
        org.junit.Assert.fail();
    }
    catch(RuntimeException rte) {
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

我熟悉 Mockito,但对模拟库没有偏好。基本上,如果有人能告诉我需要模拟哪些类/方法来抛出 HTTP 500 响应,我可以弄清楚如何实际实现模拟。

Lui*_*ano 4

尝试这个:

WebResource service = client.resource(uri);

WebResource serviceSpy = Mockito.spy(service);

Mockito.doThrow(new RuntimeException("500!")).when(serviceSpy).get(Mockito.any(String.class));

serviceSpy.path("rest").path("somePath")
            .accept(MediaType.TEXT_HTML).get(String.class);
Run Code Online (Sandbox Code Playgroud)

我不知道 jersey,但根据我的理解,我认为实际的调用是在调用 get() 方法时完成的。因此,您可以只使用真实的 WebResource 对象并替换方法的行为get(String)以引发异常,而不是实际执行 http 调用。