当前位置: 首页 > news >正文

异步校验工具 awaitility

1.什么是awaitility ?

Awaitility 是一个用于 Java 的小型领域特定语言(DSL),主要用于简化和管理异步操作的同步问题。它的主要作用包括:

  1. 等待异步操作完成:在测试异步代码时,Awaitility 可以帮助你等待某个条件变为真,而不需要使用复杂的线程管理或轮询机制。

  2. 提高测试的可读性:通过使用流畅的 API,Awaitility 使得测试代码更易于阅读和理解。

  3. 减少测试中的线程问题:避免在测试中显式地使用Thread.sleep(),从而减少不必要的等待时间和线程问题。

  4. 灵活的超时和轮询间隔:允许你设置自定义的超时时间和轮询间隔,以便更好地控制等待条件的检查频率。

总之,Awaitility 使得在测试异步操作时更加简单和直观,特别是在需要等待某个条件满足的情况下。

2.代码工程

实验目的

一个使用 Awaitility 的简单示例,演示如何等待异步操作完成。假设我们有一个异步任务,该任务在后台线程中更新一个标志,我们希望在测试中等待这个标志变为true

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>Java-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>Awaitility</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><dependencies><!-- Awaitility dependency --><dependency><groupId>org.awaitility</groupId><artifactId>awaitility</artifactId><version>4.2.0</version></dependency><!-- JUnit dependency for testing --><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.8.2</version><scope>test</scope></dependency></dependencies></project>

AwaitilityExample

  1. 异步任务:startAsyncTask方法启动一个异步任务,该任务在 5秒后将flag设置为true

  2. Awaitility 使用:在main方法中,我们使用 Awaitility 的await()方法来等待flag变为true。我们设置了一个最大等待时间为 5 秒。

  3. 条件检查:until(example::isFlag)表示我们等待example.isFlag()返回true

ackage com.et;import org.awaitility.Awaitility;import java.util.concurrent.TimeUnit;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class AwaitilityExample {private volatile boolean flag = false;public void startAsyncTask() {ExecutorService executor = Executors.newSingleThreadExecutor();executor.submit(() -> {try {// mock asyncThread.sleep(5000);flag = true;} catch (InterruptedException e) {Thread.currentThread().interrupt();}});executor.shutdown();}public boolean isFlag() {return flag;}public static void main(String[] args) {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();// use Awaitility to wait flag for trueAwaitility.await().atMost(5, TimeUnit.SECONDS).until(example::isFlag);System.out.println("Flag is now true!");}}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/Java-demo(awaitility )

3.测试代码

3-1.默认等待时间

await().until(Callable conditionEvaluator) 最多等待 10s 直到 conditionEvaluator 满足条件,否则 ConditionTimeoutException。

public void testAsynchronousNormal() {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();try {// Default timeout is 10 seconds. If the condition is not met within this period, a ConditionTimeoutException is thrownAwaitility.await().until(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {return example.isFlag();}});} catch (Exception e) {Assertions.fail("Run exception: " + e.getMessage() + ", error: " + e.getStackTrace()[0].toString());}}

3-2.最多等待

await().atMost() 设置最多等待时间,如果在这时间内条件还不满足,将抛出 ConditionTimeoutException。

@Testpublic void testAsynchronousAtMost() {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();try {// Specify a timeout of 3 seconds. If the condition is not met within this period, a ConditionTimeoutException is thrownAwaitility.await().atMost(3, SECONDS).until(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {return example.isFlag();}});} catch (Exception e) {Assertions.fail("Run exception: " + e.getMessage() + ", error: " + e.getStackTrace()[0].toString());}}

3-3.至少等待

await().atLeast() 设置至少等待时间;多个条件时候用 and() 连接。

@Testpublic void testAsynchronousAtLeast() {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();try {// Specify at least 1 second and at most 3 seconds. If the condition is not met within this period, a ConditionTimeoutException is thrownAwaitility.await().atLeast(1, SECONDS).and().atMost(3, SECONDS).until(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {return example.isFlag();}});} catch (Exception e) {Assertions.fail("Run exception: " + e.getMessage() + ", error: " + e.getStackTrace()[0].toString());}}

3-4.轮询

with().pollInterval(ONE_HUNDRED_MILLISECONDS).and().with().pollDelay(50, MILLISECONDS) that is conditions are checked after 50ms then 50ms+100ms。

@Testpublic void testAsynchronousPoll() {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();try {// Polling query, pollInterval specifies how often to poll, pollDelay specifies the delay between each pollAwaitility.with().pollInterval(ONE_HUNDRED_MILLISECONDS).and().with().pollDelay(50, MILLISECONDS).await("count is greater 3").until(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {return example.isFlag();}});} catch (Exception e) {Assertions.fail("Run exception: " + e.getMessage() + ", error: " + e.getStackTrace()[0].toString());}}

3-5.Fibonacci 轮询

with().pollInterval(fibonacci(SECONDS)) 非线性轮询,按照 fibonacci 数轮询。

@Testpublic void testAsynchronousFibonacciPoll() {AwaitilityExample example = new AwaitilityExample();example.startAsyncTask();try {// Use Fibonacci numbers as the interval: 1, 1, 2, 3, 5, 8,..., default unit is millisecondsAwaitility.with().pollInterval(fibonacci(SECONDS)).await("count is greater 3").until(new Callable<Boolean>() {@Overridepublic Boolean call() throws Exception {return example.isFlag();}});} catch (Exception e) {Assertions.fail("Run exception: " + e.getMessage() + ", error: " + e.getStackTrace()[0].toString());}}

4.引用

  • https://github.com/awaitility/awaitility

  • https://www.liuhaihua.cn/archives/711844.html

http://www.cnnetsun.cn/news/15524.html

相关文章:

  • 5种方法彻底解决番茄小说离线下载难题
  • 史诗级漏洞警报:ASP.NET Core 被曝 CVSS 9.9 分漏洞,几乎所有.NET 版本无一幸免!
  • Cider音乐播放器终极指南:跨平台Apple Music体验全解析
  • 力扣刷题:最大子数组和
  • ⭐力扣刷题:岛屿数量
  • Screenbox媒体播放器:深度解析Windows平台的现代播放解决方案
  • 5步重构OpenSTM扫描隧道显微镜项目架构
  • DXVK终极配置手册:Linux游戏性能优化的完整解决方案
  • 活字格低代码平台:企业数字化转型的技术架构与实践剖析
  • NVIDIA CUDA 13.1权威指南:CUDA Tile驱动下一代GPU编程,性能全面提升
  • Figma中文界面完整指南:快速实现设计工具本地化
  • 重新定义AI视觉评估:多维度评分系统深度解析
  • Hap视频编解码器:专业级QuickTime硬件加速终极指南
  • 阿里Wan2.1开源:消费级GPU如何重塑视频创作生态
  • 40亿参数改写边缘AI规则:Qwen3-VL-4B-Thinking-FP8轻量化多模态革命
  • MATLAB图像导出专业指南:掌握export_fig的核心技术
  • AI浪潮下的新职业生态:技术角色的系统性演化
  • SQL优化实战:标量子查询改写外连接的真实案例
  • Claude Code 杀疯了!首创“后台实习生”模式,这才是真正的 AI 结对编程!
  • 多进程环境中解决 PHP 文件系统锁定问题指南
  • 浅谈InheritableThreadLocal---线程可继承的小书包
  • Jellyfin Android TV客户端音频播放异常问题深度解析
  • HFI高频方波注入方案stm32f405 无感FOC控制 直接闭环启动 永磁同步电机无感控制...
  • CTR预测系统构建实战:从FM到DeepFM的推荐算法演进之路
  • 从零玩转RT-Thread(22):定时器底层机制揭秘
  • B站缓存视频转换完整教程:m4s-converter高效管理本地视频
  • 解锁企业级后台管理:用Vue.js和Element-UI构建高效前端解决方案
  • WMS 和 ERP 先上哪个?行业内幕:仓库没打好地基,什么 ERP 都白搭
  • WiFi放大器小白指南:从选购到安装的完整教程
  • AI如何革新虚拟光驱开发?自动化代码生成实战