首页 > 解决方案 > vertx 单元测试未执行,超时异常

问题描述

我有以下简单的重试类。此类将在给定的延迟(延迟)内重试给定的承诺几次(retryCount),如果在重试计数内成功,则通过,否则失败。

public class SimpleRetry {

  private final Vertx vertx;

  public SimpleRetry(Vertx vertx) {
    this.vertx = vertx;
  }

  
  public <T> Promise<T> retryWithDelay(Promise<T> promise, int retryCount, int delay, TimeUnit unit) {
    log.debug("Retrying operation with : " + retryCount + " retry count and delay of " + delay);
    return execute(promise, retryCount, delay, unit);
  }


  private <T> Promise<T> execute(Promise<T> promise, int count, int delay, TimeUnit unit) {
    Promise<T> newPromise = Promise.promise();
    if (count > 0) {
      promise.future().onComplete(handler -> {
        if (handler.succeeded()) {
          log.debug("Retry operation successful");
          newPromise.complete(handler.result());
        } else {
          log.debug("Operation failed, hence retrying again..");
          if (delay > 0) {
            vertx.setTimer(unit.toMillis(delay), id -> execute(promise, count - 1, delay, unit));
          } else {
            execute(promise, count - 1, delay, unit);
          }
        }
      });
    } else {
      log.debug("Retry count exceeded, hence failing the promise..");
      newPromise.fail("Retry count exceeded!.");
    }
    return newPromise;
  }

写了下面的测试用例来测试它。但它不会被执行。相反,它超时。

@RunWith(VertxUnitRunner.class)
public class SimpleRetryTests {

  private SimpleRetry simpleRetry;
  private Vertx vertx;
  private static int count;

  @Before
  public void setUp(TestContext context){
    vertx = Vertx.vertx();
    simpleRetry = new SimpleRetry(vertx);
    count = 0;
    context.asyncAssertSuccess();
  }

  @Test
  public void testSimpleRetryWhichPassesOnFirstTry(TestContext context){
    final Async async = context.async();
    simpleRetry.retryWithDelay(dummyPromise(1), 10, 10, TimeUnit.MILLISECONDS)
        .future().onSuccess(res -> {
      System.out.println("Promise completed");
      context.asyncAssertSuccess();
      async.complete();
    }).onFailure(ex -> {
      System.out.println("Promise failed : " + ex);
      context.asyncAssertFailure();
      async.complete();
    });
  }

  //A dummy promise which only passes when called 5 times.
  private Promise<Void> dummyPromise(int passCount){
    Promise<Void> promise = Promise.promise();
    vertx.setTimer(10, id->{
      count++;
      if(count == passCount) {
        promise.complete();
      } else {
        promise.fail("Error!!");
      }
    });
    return promise;
  }

  @After
  public void tearDown(TestContext context){
    simpleRetry = null;
    vertx.close(context.asyncAssertSuccess());
  }
}

我究竟做错了什么?提前致谢。

标签: unit-testingxunitvert.x

解决方案


您误用了context.asyncAssertSuccess()context.asyncAssertFailure()它会停止您的代码,例如您的 setUp 函数将永远不会退出。把它们拿出来,你的测试就会通过。


推荐阅读