How many mistakes can you find about assertions in this test script?
@Test
public void searchTest() throws InterruptedException, IOException {
try {
driver.get(HOME_PAGE_URL);
String homePageUrl = driver.getCurrentUrl();
Assert.assertTrue(homePageUrl.equals(HOME_PAGE_URL));
WebElement searchBox = driver.findElement(SEARCH_BOX_ID);
searchBox.sendKeys(KEYWORD);
WebElement searchButton = driver.findElement(SEARCH_BUTTON_ID);
searchButton.click();
String resultsPageUrl = driver.getCurrentUrl();
boolean correctUrl = resultsPageUrl.startsWith(RESULTS_PAGE_URL);
Assert.assertEquals(correctUrl, true);
boolean keywordIncluded = resultsPageUrl.contains("query=" + KEYWORD);
Assert.assertTrue(keywordIncluded == true);
WebElement resultsFoundLabel = driver.findElement(RESULTS_FOUND_XPATH);
String resultsFoundText = resultsFoundLabel.getText();
int i1 = resultsFoundText.indexOf("of") + 3;
int i2 = resultsFoundText.indexOf(" results");
int totalCount = Integer.parseInt(resultsFoundText.substring(i1, i2));
Assert.assertTrue(totalCount > 0);
}
catch (Exception e) {
System.out.println("\n\nsearch test failed!\n\n");
System.out.println("exception info \n\n" + e.getMessage() + "\n\n");
Assert.assertTrue(false);
}
If your answer was 5, you are correct.
All assertions are incorrect.
Let’s look at them one by one.
1.
Assert.assertTrue(homePageUrl.equals(HOME_PAGE_URL));
Since this is about comparing 2 string values, assertEquals() is a better fit:
Assert.assertEquals(homePageUrl, HOME_PAGE_URL);
2.
Assert.assertEquals(correctUrl, true);
Since the assertion compares 2 boolean variables, assertTrue is better than assertEquals(). Make sure that you add an error message as well to the assertion:
Assert.assertTrue(correctUrl,
String.format("%s does not start with %s", resultsPageUrl, RESULTS_PAGE_URL));
3.
Assert.assertTrue(keywordIncluded == true);
Comparing the boolean variable with true is redundant. Simplify the assertion by removing the comparison and add an error message:
Assert.assertTrue(keywordIncluded,
String.format("%s does not contain query = %s", resultsPageUrl, KEYWORD));
4.
Assert.assertTrue(totalCount > 0);
Just add the error message:
Assert.assertTrue(totalCount > 0, totalCount + " is not > 0");
5.
Assert.assertTrue(false);
Use instead:
Assert.fail("search test failed);
In summary,
use only assertEquals when comparing 2 values
do not use assertEquals to compare a boolean value to true
use assertTrue when checking if a boolean value is equal to true; otherwise, use assertFalse
do not compare a boolean value to true when using the assertTrue method
use fail() to fail the test
add an error message to all assertTrue methods
use string formatting for creating the error messages