首页 > 解决方案 > 如果处理程序中有要模拟的对象,则对 vertx 响应处理程序进行单元测试

问题描述

示例响应处理程序:

private static void handleGetRequest(RoutingContext ctx) {
    final HttpServerResponse response = ctx.response;
    try {
        A a = B.getSomeA();
        a.handleSomething();
    }
    catch (Exception ex) {System.out.println(ex);}
}

我们如何通过在处理程序中模拟对象来对上述处理程序进行单元测试?

标签: vert.xvertx-verticlevertx-httpclient

解决方案


您需要引入一个接缝,其中的实例A提供给Handler. 这样的接缝允许您引入 mocks/stubs/fakes 用于测试目的。

解决方案可能很简单:

  class MyHandler implements Handler<RoutingContext> {
    private final Supplier<A> aSupplier;

    MyHandler(Supplier<A> aSupplier) { // <-- this is your test seam
      this.aSupplier = aSupplier;
    }

    @Override
    public void handle(RoutingContext ctx) {
      final HttpServerResponse response = ctx.response();
      try {
        A a = aSupplier.get(); // <-- a mocked version can return 'A' in any state
        a.handleSomething();
      }
      catch (Exception ex) {System.out.println(ex);}
    }
  }

将 out分离Handler为自己的类型会带来额外的好处,即能够单独测试它,但这并不是绝对必要的。


推荐阅读