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.>>
错误原因
- 预期值错误:错误信息里的尖括号是断言框架用来区分预期/实际值的标记,并非页面文本本身,你错误地将其写入了预期值中。
- 文本含空白字符:页面元素的文本前后存在空格,直接调用
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
相关产品推荐
相关产品推荐

