我正在编写一个使用 Jersey 的 Java 类在后台向 RESTful API(第 3 方)发送 HTTP 请求。
我还想编写一个 JUnit 测试来模拟 API 发回 HTTP 500 响应。作为 Jersey 的新手,我很难明白我必须做什么来模拟这些 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) {
;
}
}
我熟悉 Mockito,但对模拟库没有偏好。基本上,如果有人能告诉我需要模拟哪些类/方法来抛出 HTTP 500 响应,我就能弄清楚如何实际实现模拟。
最佳答案
试试这个:
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);
我不知道 Jersey ,但根据我的理解,我认为实际调用是在调用 get() 方法时完成的。
因此,您可以只使用真正的 WebResource 对象并替换 get(String)
方法的行为以抛出异常,而不是实际执行 http 调用。
关于java - 如何模拟 Jersey REST 客户端以抛出 HTTP 500 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016154/