You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AssertJ JUnitSoftAssertions时如何等待页面加载?

解决JUnitSoftAssertions中页面跳转后URL断言失败的问题

你可以利用Selenium的**显式等待(WebDriverWait)**来解决这个问题,它会智能等待指定条件满足后再执行后续逻辑,完全替代不推荐的Thread.sleep()。

方案1:直接等待目标URL加载完成

在点击按钮后,先通过显式等待确认当前URL已经切换到目标页面,再执行断言。这样既符合逻辑,又能避免页面加载慢导致的断言失败。

修改后的代码示例:

import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

@Rule
public final JUnitSoftAssertions softly = new JUnitSoftAssertions();

@And("he should be on {page} page")
public void gotoPage(String page) {
  // 当前页面为A,点击跳转到页面B
  toPageBButton.click();
  
  // 显式等待URL变为目标页面地址,超时时间设为10秒(可根据实际调整)
  new WebDriverWait(driver, Duration.ofSeconds(10))
      .until(ExpectedConditions.urlToBe(page));
  
  // 执行URL断言
  softly.assertThat(driver.getCurrentUrl()).as("Page B").isEqualTo(page);
  softly.assertAll();
}

方案2:等待页面完全加载(可选)

如果遇到URL已切换但页面资源未加载完成的场景,还可以通过等待页面的document.readyState变为complete来确保页面加载完毕:

new WebDriverWait(driver, Duration.ofSeconds(10))
    .until(driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete"));

显式等待的优势在于它会轮询检查条件,一旦满足就立即执行后续代码,不会像Thread.sleep()那样固定等待时间,既高效又能适配不同的加载速度。

内容的提问来源于stack exchange,提问作者Ragnarsson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:13:12