We all do text validation in our automation tests to validate whether the returned value is the same as the expected one or not. I see that many folks use the assertTrue command instead of assertEquals to validate the returned text while using assertions from TestNG or JUnit. Let’s see why using assertTrue is bad practice for text comparison.
assertEquals:
public static void assertEquals(String actual, String expected)
Asserts that two Strings are equal. If they are not, an AssertionError is thrown.
Parameters:
- actual – the actual value
- expected – the expected value
assertTrue:
public static void assertTrue(boolean condition)
Asserts that a condition is true. If it isn’t, an AssertionError is thrown.
Parameters:
- condition – the condition to evaluate
Let’s say that I have an automated test script where I would like to verify the Title of the home page of https://softwaretestingjournal.com/ – we are doing the check using assertTrue as well as assertEquals methods.
String ExpectedTitle = “My Home – Software Testing Journal”;
@Test
public void verifyTitleUsingTrue() {
assertTrue(driver.getTitle().equals(ExpectedTitle));
}
@Test
public void verifyTitleUsingEquals() {
assertEquals(driver.getTitle(), ExpectedTitle);
}
Note* The actual result of driver.getTitle() will be “Home – Software Testing Journal” but the expected one is “My Home – Software Testing Journal”.
When you execute this, it will fail as expected and you will see an error message like this for assertTrue:
FAILED: verifyTitleUsingTrue
java.lang.AssertionError: expected [true] but found [false]
Were you able to understand the problem through the error message? I doubt that.
And this is the error message you will see for assertEquals:
FAILED: verifyTitleUsingEquals
java.lang.AssertionError: expected [My Home – Software Testing Journal] but found [Home – Software Testing Journal]
As you can see that the use of assertEquals makes it much easier to understand what the actual difference between the expected and actual results is. Also, we can catch the failure without opening the code and trying to search for the text differences. So, use the proper method as per the context 🙂