如何使用JUnit在Selenium中断言元素包含文本

8

我有一个页面,我知道在某个xpath下会包含特定的文本。在Firefox中,我使用以下代码来断言该文本是否存在:

assertEquals("specific text", driver.findElement(By.xpath("xpath)).getText());

我正在确认在表单中添加了某个附件并断言表单的第二步。然而,当我在 Chrome 中使用相同的代码时,显示输出内容不同,但确实包含了特定的文本。我得到以下错误:
org.junit.ComparisonFailure: expected:<[]specific text> but was:<[C:\fakepath\]specific text>

不要使用断言来表明某个事实是真实的(这正是我所需要的),我想写出类似于:

assert**Contains**("specific text", driver.findElement(By.xpath("xpath)).getText());

上述代码显然无法正常工作,但我找不到实现它的方法。

使用Eclipse、Selenium WebDriver和Java。


我相信这个问题已经在这里得到了回答:https://dev59.com/4HNA5IYBdhLWcg3wGJwV - stackhelper101
4个回答

19

使用:

String actualString = driver.findElement(By.xpath("xpath")).getText();
assertTrue(actualString.contains("specific text"));

您还可以使用以下方法,使用assertEquals

String s = "PREFIXspecific text";
assertEquals("specific text", s.substring(s.length()-"specific text".length()));
忽略字符串中不需要的前缀。

2
谢谢!我使用了以下代码,运行得很好: assertTrue(driver.findElement(By.xpath("xpath")).getText().contains("specific text")); - Hugo
1
你可以选择添加第二个参数,用于自定义错误信息以便在失败时使用。例如:assertTrue(s.contains("specific text"), "String did not contain the required text."); - Andrio

2

可以使用两种方法,assertEquals和assertTrue。以下是用法:

String actualString = driver.findElement(By.xpath("xpath")).getText();

String expectedString = "ExpectedString";

assertTrue(actualString.contains(expectedString));

我知道这是一篇旧帖,但有没有人用C#做过同样的事情?我很想看看那段代码。 - user1622681

2

你也可以使用这段代码:

String actualString = driver.findElement(By.xpath("xpath")).getText();
Assert.assertTrue(actualString.contains("specific text"));

0

这与assert不直接相关,另一种方法是使用wait.untilExpectedCondition,如果条件不满足,则测试将失败:

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    @FindBy(xpath = "xpath")
    private WebElement xpathElementToCheckText;
      
    public void checkElementText() {
       WebDriverWait wait = new WebDriverWait(driver, 10); // timeout in seconds
wait.until(ExpectedConditions.textToBePresentInElement(xpathElementToCheckText,"specific text"));
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接