Vert.x 对未实现 start 方法的 Verticle 进行单元测试

Vert.x Unit Test a Verticle that does not implement the start method with future

我是 Vert.x 的新手,刚遇到一个问题。 我有以下 Verticle:

public class HelloVerticle extends AbstractVerticle {

  @Override
  public void start() throws Exception {

    String greetingName = config().getString("greetingName", "Welt");
    String greetingNameEnv = System.getenv("GREETING_NAME");
    String greetingNameProp = System.getProperty("greetingName");

    Router router = Router.router(vertx);
    router.get("/hska").handler(routingContext -> {
        routingContext.response().end(String.format("Hallo %s!", greetingName));
    });
    router.get().handler(routingContext -> {
        routingContext.response().end("Hallo Welt");
    });

    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(8080);
  }
}

我想对这个 Verticle 进行单元测试,但我不知道如何等待 Verticle 部署。

@Before
public void setup(TestContext context) throws InterruptedException {
    vertx = Vertx.vertx();
    JsonObject config = new JsonObject().put("greetingName", "Unit Test");

    vertx.deployVerticle(HelloVerticle.class.getName(), new DeploymentOptions().setConfig(config));
}

当我像这样设置我的测试时,我必须在部署调用之后添加一个 Thread.sleep,以便在等待 Verticle 一段时间后执行测试。

我听说了 Awaitability,应该可以等待 Verticle 与这个库一起部署。但是我没有找到任何关于如何将 Awaitability 与 vertx-unit 和 deployVerticle 方法一起使用的示例。

谁能对此有所启发?

或者我真的必须在测试中调用 deployVerticle-方法后硬编码睡眠定时器吗?

查看已接受答案的评论

首先你需要实现 start(Future future) 而不仅仅是 start()。然后您需要向 listen(...) 调用添加一个回调处理程序 (Handler<AsyncResult<HttpServer>> listenHandler) — 然后解析您通过 start(Future future).

获得的 Future

Vert.x 是高度异步的——Vert.x HTTP 服务器的启动也是如此。在您的情况下,当 HTTP 服务器成功启动时,Verticle 将完全正常运行。因此,你需要实现我上面提到的东西。

其次,您需要告诉 TestContext 您的 Verticle 的异步部署已完成。这可以通过另一个回调处理程序 (Handler<AsyncResult<String>> completionHandler) 来完成。 blog post 展示了如何做到这一点。 即使您实现了普通的 start() 方法,Verticle 的部署始终是异步的。因此,如果您想确保您的 Verticle 在测试前已成功部署,则应始终使用 completionHandler

所以,不,你不需要,你绝对不应该在你的任何 Vert.x 应用程序中硬编码睡眠定时器。头脑The Golden Rule - Don’t Block the Event Loop.

编辑:

如果您的 Verticle 初始化是同步的,您应该覆盖普通的 start() 方法 — like it's mentioned in the docs:

If your verticle does a simple, synchronous start-up then override this method and put your start-up code in there.

如果您的 Verticle 初始化是异步的(例如部署 Vert.x HTTP 服务器),您应该在异步初始化完成后覆盖 start(Future future) 并完成 Future