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

Java Selenium获取Toast文本断言失败问题求助

Selenium断言失败问题解决

问题场景

需要从以下HTML中提取文本Nothing entered.:

<div class="ng-tns-c170-53 ng-star-inserted ng-trigger ng-trigger-flyInOut ngx-toastr toast-warning" toast-component="" style="opacity: 1;">
<button type="button" aria-label="Close" class="toast-close-button ng-tns-c170-53 ng-star-inserted" style=""><span aria-hidden="true" class="ng-tns-c170-53">×</span></button><!----><!----><!----><div role="alert" class="ng-tns-c170-53 toast-message ng-star-inserted" aria-label="Nothing entered." style=""> Nothing entered. </div><!----><!----></div>

使用以下Selenium代码断言时失败:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
WebElement nothingEnteredErrorMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"toast-container\"]/div[1]/div")));
assertEquals(nothingEnteredErrorMessage.getText(), "<Nothing entered.>");

错误提示:

org.opentest4j.AssertionFailedError: expected: <Nothing entered.> but was: <<Nothing entered.>>

错误原因

  1. 预期值错误:错误信息里的尖括号是断言框架用来区分预期/实际值的标记,并非页面文本本身,你错误地将其写入了预期值中。
  2. 文本含空白字符:页面元素的文本前后存在空格,直接调用getText()会带回这些空格,导致与无空格的预期值不匹配。

解决方案

1. 修正断言代码

去掉预期值的尖括号,同时用trim()方法去除文本前后空白:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
WebElement nothingEnteredErrorMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"toast-container\"]/div[1]/div")));
// 去除前后空白后再执行断言
assertEquals(nothingEnteredErrorMessage.getText().trim(), "Nothing entered.");

2. 优化元素定位(可选)

原XPath依赖页面层级结构,易受页面变动影响,建议使用更稳定的定位方式:

  • 利用aria-label属性定位:
By errorLocator = By.xpath("//div[@aria-label='Nothing entered.']");
  • 利用toast-message类名定位:
By errorLocator = By.cssSelector(".toast-message");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:48:27