news 2026/6/10 12:05:22

异步校验工具 awaitility

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
异步校验工具 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

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/9 7:17:11

Windows 10 OneDrive彻底卸载技术指南

Windows 10 OneDrive彻底卸载技术指南 【免费下载链接】OneDrive-Uninstaller Batch script to completely uninstall OneDrive in Windows 10 项目地址: https://gitcode.com/gh_mirrors/one/OneDrive-Uninstaller 微软OneDrive在Windows 10系统中深度集成&#xff0c;…

作者头像 李华
网站建设 2026/6/9 2:19:11

漫画下载神器:BiliBili-Manga-Downloader完整使用攻略

还在为漫画下载而烦恼吗&#xff1f;这款终极漫画下载工具能帮你轻松解决所有难题&#xff01;BiliBili-Manga-Downloader作为一款专业的漫画下载利器&#xff0c;不仅拥有强大的图形界面&#xff0c;更支持多线程高速下载&#xff0c;让你的漫画收藏之路变得简单高效。 【免费…

作者头像 李华
网站建设 2026/6/9 5:28:02

36_Spring AI 干货笔记之 Mistral AI 嵌入

一、Mistral AI 嵌入 Spring AI 支持 Mistral AI 的文本嵌入模型。嵌入是文本的向量化表示&#xff0c;通过在高维向量空间中的位置来捕获段落的语义含义。Mistral AI 嵌入 API 为文本提供尖端、最先进的嵌入&#xff0c;可用于许多自然语言处理任务。 二、可用模型 Mistral…

作者头像 李华
网站建设 2026/6/7 20:54:53

亲测有效!DC-DC 电源啸叫不用慌

前言&#xff1a;做硬件开发的朋友&#xff0c;是否遇到过这种糟心场景&#xff1a;精心打样回来的板子一上电&#xff0c;就传来“滋滋”“嗡嗡”的啸叫声&#xff0c;刹时心里发慌——不会“罢工”吧&#xff1f;别慌&#xff0c;几乎是每一位硬件工程师都会遇到的“经典难题…

作者头像 李华
网站建设 2026/6/9 6:34:52

【光照】UnityURP[屏幕空间环境光遮蔽SSAO]原理剖析实践

AO&#xff08;Screen Space Ambient Occlusion&#xff0c;屏幕空间环境光遮蔽&#xff09;是Unity URP中用于模拟物体间环境光遮蔽效果的技术&#xff0c;通过计算像素周围几何体的遮挡关系增强场景深度感和真实感。技术发展进程‌早期阶段‌&#xff1a;传统SSAO算法如Cryte…

作者头像 李华
网站建设 2026/6/9 12:29:55

让MacBook刘海屏变身音乐舞台:Boring.Notch完全指南

让MacBook刘海屏变身音乐舞台&#xff1a;Boring.Notch完全指南 【免费下载链接】boring.notch TheBoringNotch: Not so boring notch That Rocks &#x1f3b8;&#x1f3b6; 项目地址: https://gitcode.com/gh_mirrors/bor/boring.notch 你是不是总觉得MacBook那个刘海…

作者头像 李华