我正在使用rxjava vert.x (版本3.8.4) WebClient。我的客户将调用一些服务,因此,由Mockito (版本。3.2.4)我正在测试它应该如何处理错误。下面是我模拟服务响应的方式:
...
JsonObject jsonResponse = new JsonObject();
HttpResponse<Buffer> httpResponse = Mockito.mock(HttpResponse.class);
Mockito.when(httpResponse.statusCode()).thenReturn(500);
Mockito.when(httpResponse.bodyAsJsonObject()).thenReturn(jsonResponse);
HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class);
Mockito.when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse));
return httpRequest;
...在执行Mockito.when(httpResponse.statusCode()).thenReturn(500);时,我得到了这个错误:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at my.dummy.project.ServiceHandlerTest.serviceRepliesWithA500Response(ServiceHandlerTest.java:70)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
...这里我漏掉了什么?
发布于 2020-01-29 19:37:55
我的建议是在这种测试用例中使用okhttp的MockWebServer。
可以为每个测试实例化MockWebserver,并允许您创建一个webservice,以便被测试的实现用来发送针对它的真实http请求。
在此之前,您可以定义一个mock响应,该响应将由mockwebserver返回给您的实现。
我不知道您的测试用例,但这段代码应该可以清楚地说明MockWebServer是如何工作的。
更多的例子和完整的文档可以在their github repo找到。
正如你在下面看到的,你可以做几个断言,例如。如果使用了正确的请求方法,则触发了多少个请求,以及在请求过程中是否使用了正确的请求参数和body。
@ExtendWith(VertxExtension.class)
@Slf4j
public class WebServiceTest {
private WebServiceRequester sut;
private MockWebServer mockWebServer;
@BeforeEach
public void setUp() {
sut = new WebServiceRequester();
mockWebServer = new MockWebServer();
}
@Test
public void testCallService(final Vertx vertx, final VertxTestContext testContext) throws InterruptedException {
// given
final JsonObject requestPayload = new JsonObject().put("requestData", new JsonArray("[]"));
final JsonObject serverResponsePayload = new JsonObject().put("responseData", new JsonArray("[]"));
mockWebServer.enqueue(new MockResponse()
.setBody(serverResponsePayload.encode())
.setResponseCode(200)
.setHeader("content-type", "application/json"));
// when
final String webServiceUrl = mockWebServer.url("/").toString();
final Promise<String> stringPromise =
sut.callService(
webServiceUrl,
requestPayload,
vertx);
// then
final RecordedRequest recordedRequest = mockWebServer.takeRequest();
assertEquals("POST", recordedRequest.getMethod());
assertEquals("[text={\"request\":[]}]", recordedRequest.getBody().toString());
assertEquals(1, mockWebServer.getRequestCount());
testContext.assertComplete(stringPromise.future())
.map(val -> {
assertEquals("promise_completed", val);
testContext.completeNow();
return val;
})
.onComplete(onComplete -> {
assertTrue(onComplete.succeeded());
log.info("done");
})
.onFailure(onError -> Assertions.fail());
}
}https://stackoverflow.com/questions/59957813
复制相似问题