【问题标题】:How to assert elements contains text in Selenium using JUnit如何使用 JUnit 断言元素包含 Selenium 中的文本
【发布时间】:2015-12-29 12:03:37
【问题描述】:

我有一个页面,我知道它在某个 xpath 中包含某个文本。在 Firefox 中,我使用以下代码断言文本存在:

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

我在表单中声明第 2 步,并确认某个附件已添加到表单中。 但是,当我在 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

【问题讨论】:

标签: java eclipse selenium junit assert


【解决方案1】:

用途:

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()));

忽略字符串中不需要的前缀。

【讨论】:

  • 谢谢!我使用了以下内容并且效果很好: assertTrue(driver.findElement(By.xpath("xpath")).getText().contains("specific text"));
  • 您可以选择添加第二个参数,如果失败,则带有自定义错误消息。例如:assertTrue(s.contains("specific text"), "String did not contain the required text.");
【解决方案2】:

您也可以使用此代码:

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

【讨论】:

    【解决方案3】:

    可以使用两种方法 assertEquals 和 assertTrue。 这是用法

    String actualString = driver.findElement(By.xpath("xpath")).getText();
    
    String expectedString = "ExpectedString";
    
    assertTrue(actualString.contains(expectedString));
    

    【讨论】:

    • 我知道这是一篇旧文章,但有人在 C# 中做过同样的事情吗?我很想看到那个代码。
    猜你喜欢
    • 1970-01-01
    • 2018-04-28
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多