How to assert elements contains text in Selenium using JUnit How to assert elements contains text in Selenium using JUnit selenium selenium

How to assert elements contains text in Selenium using JUnit


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.


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

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


You can also use this code:

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