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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32887492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:59:27  来源:igfitidea点击:

How to assert elements contains text in Selenium using JUnit

javaeclipseseleniumjunitassert

提问by Hugo

I have a page that I know contains a certain text at a certain xpath. In firefox I use the following code to assert that the text is present:

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

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

I'm asserting step 2 in a form and confirming that a certain attachment has been added to the form. However, when I use the same code in Chrome the displayed output is different but does contain the specific text. I get the following error:

我在表单中声明步骤 2 并确认某个附件已添加到表单中。但是,当我在 Chrome 中使用相同的代码时,显示的输出不同,但确实包含特定文本。我收到以下错误:

org.junit.ComparisonFailure: expected:<[]specific text> but was:<[C:\fakepath\]specific text>

Instead of asserting something is true (exactly what I'm looking for) I'd like to write something like:

我不想断言某事是真的(正是我正在寻找的),我想写一些类似的东西:

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

The code above does not work obviously but I can't find how to get this done.

上面的代码显然不起作用,但我找不到如何完成这项工作。

Using Eclipse, Selenium WebDriver and Java

使用 Eclipse、Selenium WebDriver 和 Java

采纳答案by ROMANIA_engineer

Use:

用:

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

You can also use the following approach, using assertEquals:

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

String s = "PREFIXspecific text";
assertEquals("specific text", s.substring(s.length()-"specific text".length()));

to ignore the unwanted prefix from the string.

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

回答by Vaibhav

You can also use this code:

您也可以使用此代码:

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

回答by Meenakshi Rana

Two Methods assertEquals and assertTrue could be used. Here is the usage

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

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

String expectedString = "ExpectedString";

assertTrue(actualString.contains(expectedString));