assertTrue() does not throw AssertionError
I’m using assertTrue() to check if the button exists.
Assert.assertTrue(isElementPresent(By.cssSelector(or.getProperty("addCustomerButton"))));
addCustomerButton
contains a locator for the button.
The isElementPresent() code is
:
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch(NoSuchElementException e) {
return false;
}
}
When findElement()
in the try block of the isElementPresent
() method does not find an element, findElement()
must throw the exception NoSuchElementException
. I caught the exception in the catch block. If
isElementPresent()
returns true, the assertion is true
and no AssertionError
is thrown. If isElementPresent()
returns false, the assertion is false
and AssertionError
should be thrown, right?
But in my script above, AssertionError
is not thrown. The test is marked as passed.
Update:
After repeated modification execution, throw AssertionError
Test — failed
com.datadriven.testcases.BankManagerLoginTest loginAsBankManager 1542342446849 10126
Test
com.datadriven.testcases.BankManagerLoginTest#loginAsBankManager
Exception
java.lang.AssertionError: expected [true] but found [false]
at com.datadriven.testcases.BankManagerLoginTest.loginAsBankManager(BankManagerLoginTest.java:17)
... Removed 29 stack frames
I’ve changed the locator from button[ng-click=’addCust()'] to button[ng-click=
‘addCus'].
Solution
You are right, if the condition is false, you should expect the test to fail by throwing AssertionError
.
However, if any exception is thrown, the test will fail, so all you need to do is
this
// throws an NoSuchElementException if it fails
driver.findElement(By.cssSelector(or.getProperty("addCustomerButton")));
In this case, you expect the missing entry to cause an error or exception. In this way, you should get a more meaningful message explaining why the test failed.
If you want to use a method to know more clearly what is being tested, you can write like this
public static void assertNoException(Object o) { }
assertNoException(driver.findElement(By.cssSelector(or.getProperty("addCustomerButton"))));