测试executeBlocking的结果

时间:2017-12-04 04:31:50

标签: unit-testing vert.x

我有一个vertx处理程序代码,我在其中执行executeBlocking但为了使其工作,我需要输入Thread.sleep(),以便阻塞代码中的代码完全执行到我可以查看结果。

有没有更好的解决方法,所以我不做Thread.sleep

My handler code以下是我只保留相关组件的部分。

    try (final VertxHttpResponse response = new VertxHttpResponse(context)) {
        context.vertx().executeBlocking(
            future -> {
                ...
                try {
                    dispatcher.invokePropagateNotFound(request,
                        response);
                    future.complete();
                } finally {
                    ...
                }
            }, false,
            res -> {
                if (res.failed()) {
                    context.fail(wae);
                } else {
                    if (!context.response().ended()) {
                        context.response().end();
                    }
                }
            });
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }

}

My test及相关部分

@Test
public void test(final TestContext testContext) throws Exception {

    final Router router = Router.router(rule.vertx());
    final SpringJaxRsHandler handler = SpringJaxRsHandler.registerToRouter(router, MyApp.class);
    final RoutingContext routingContext = mock(RoutingContext.class);
    when(routingContext.currentRoute()).thenReturn(router.get("/api/hello"));
    when(routingContext.vertx()).thenReturn(rule.vertx());

    final HttpServerRequest serverRequest = mock(HttpServerRequest.class);
    when(serverRequest.absoluteURI()).thenReturn("/api/hello");
    when(serverRequest.isEnded()).thenReturn(true);
    when(serverRequest.method()).thenReturn(HttpMethod.GET);
    when(routingContext.request()).thenReturn(serverRequest);

    final HttpServerResponse response = mock(HttpServerResponse.class);
    when(response.putHeader(anyString(), anyString())).thenReturn(response);
    when(response.headers()).thenReturn(new VertxHttpHeaders());

    when(routingContext.response()).thenReturn(response);

    handler.handle(routingContext);
    Thread.sleep(1000);
    // fails without the sleep above
    verify(response, times(1)).setStatusCode(200);

}

我试过

testContext.assertTrue(routingContext.response().ended());

但是返回了false

1 个答案:

答案 0 :(得分:0)

我稍微重构了代码,所以我不直接使用routingContext,但概念仍然相同。我将Asyncwhen->then(Answer)结合使用,并在async.complete()中调用Answer。完成后,执行async.await()等待线程完成。

    final Async async = testContext.async();
    when(response.write(Matchers.any(Buffer.class))).then(invocation -> {

        try {
            return response;
        } finally {
            async.complete();
        }
    });
    when(serverRequest.response()).thenReturn(response);

    router.accept(serverRequest);
    async.await();