Assert - 2 Exact Same String Comparing Returns Error
My guess is, that whitespace around the text are trimmed or added at getText.
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));
Probably disregard this difference:
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().trim() .equals(text.trim()));
An other property of Unicode is that é
can be either one char or two (e + accent). And java internally uses Unicode for text. Actually one should normalize text before comparing.
s = Normalizer.normalize(s, Normalizer.Form.NFKC); // Most compact
By the way instead of assertTrue
the method assertEquals
with expected and actual values will give better error messages.
Let us see whats happening in your code. You have used :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equals(text));
Within Assert.assertTrue
you are comparing 2 values. The first value is driver.findElement(By.cssSelector(cssSelector)).getText()
which can return text
(w/out white space characters) or NULL
. The second value is a pure text
.
Now, if you look at the javadoc of equals
it is defined as :
boolean java.lang.String.equals(Object anObject)//Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
This is the root case of your failure. This will return True
only if the given object represents a String
equivalent to this string
Again, if you look at the javadoc of assertTrue
it is defined as :
void org.testng.Assert.assertTrue(boolean condition)//Asserts that a condition is true. If it isn't, an AssertionError is thrown.
Solution:
The solution would be to use either contains
, equalsIgnoreCase
or contentEquals
instead of equals
as follows :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().contains(text));//ORAssert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().equalsIgnoreCase(text));//ORAssert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getText().contentEquals(text));
Update 1:
I will suggest use getAttribute("innerHTML")
instead of getText()
as follows :
Assert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").contains(text));//ORAssert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").equalsIgnoreCase(text));//ORAssert.assertTrue(driver.findElement(By.cssSelector(cssSelector)).getAttribute("innerHTML").contentEquals(text));
Update 2:
As your test is still failing, I would suggest you to reduce the expected string
to something substantial instead of the entire string. Example:
String text = "Votre commande a été";
Update 3:
As a last resort, you should be able to expand the expected string as follows :
String text = "Merci ! Votre commande a été envoyée.";
And perform your Test successfully.