java单测时的等待模块awaitility

单测时,可以用来等待异步任务完成

  在编写自动化测试用例过程中,往往会遇见被测代码有异步或者队列处理的中间过程;如果需要校验这部分结果,必须等待异步操作结束或队列消费完,而这个中间等待的时间是不确定的,常常是根据经验值设定,通过 Thread.sleep(经验值) ,而这个时间通常会设置成最长的那次时间,但是可能99%次这个异步操作都低于这个最长的时间,这就造成了每次执行这个测试用例都花费了异步任务最长的那次时间。

  现介绍一款开源工具awaitility: https://github.com/awaitility/awaitility ,该工具提供轮询的方式,判断操作是否完成,以最短的时间获取异步任务结果。

In order to use Awaitility effectively it's recommended to statically import the following methods from the Awaitility framework:

  • org.awaitility.Awaitility.*

It may also be useful to import these methods:

  • org.awaitility.Duration.*
  • java.util.concurrent.TimeUnit.*
  • org.hamcrest.Matchers.*
  • org.junit.Assert.*

If you're using Java 8 you can also use lambda expressions in your conditions:

await().atMost(5, SECONDS).until(() -> userRepository.size() == 1);

Or method references:

await().atMost(5, SECONDS).until(userRepository::isNotEmpty);

Or a combination of method references and Hamcrest matchers:

await().atMost(5, SECONDS).until(userRepository::size, is(1));

参考:

https://github.com/awaitility/awaitility/wiki/Usage

https://blog.csdn.net/hj7jay/article/details/55094639

原文地址:https://www.cnblogs.com/shengulong/p/9201096.html