Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert elements contains text in Selenium using JUnit

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:

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:

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

like image 594
Hugo Avatar asked Oct 01 '15 12:10

Hugo


People also ask

How do you assert text in Selenium?

assertText and verifyText both get the text of an element (as defined by the locator) and check if it meets the requirement of the pattern. This works for any element that contains text. Assert and verify commands are both useful for verifying condition match or not.

How do you assert values in JUnit?

assertArrayEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.


1 Answers

Use:

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

You can also use the following approach, using assertEquals:

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

to ignore the unwanted prefix from the string.

like image 153
ROMANIA_engineer Avatar answered Sep 28 '22 01:09

ROMANIA_engineer