Reputation: 681
I'm checking the presence of a button with assertTrue().
Assert.assertTrue(isElementPresent(By.cssSelector(or.getProperty("addCustomerButton"))));
addCustomerButton
contains the locator of the button.
isElementPresent()
code is:
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch(NoSuchElementException e) {
return false;
}
}
When the findElement()
in the try block of isElementPresent()
method doesn't find the element, findElement()
must throw the exception NoSuchElementException
. I caught the exception in the catch block. If the isElementPresent()
returns true
, the assertion is true
and there will be no AssertionError
thrown. If the isElementPresent()
return false
, then the assertion is false
and the AssertionError
should be thrown, right?
But in my script above, the AssertionError
is not being thrown. the test is getting marked as PASSED.
Update:
After repeated modifications and executions, AssertionError
is thrown.
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']
Upvotes: 3
Views: 1820
Reputation: 533880
You are right that if the condition is false, you should expect the test to fail by throwing an AssertionError
.
However, the test will fail if any exception is thrown so all you need to do is
// throws an NoSuchElementException if it fails
driver.findElement(By.cssSelector(or.getProperty("addCustomerButton")));
In this case, you want a missing entry to result in an Error or Exception. This way you should get a more meaningful message as to why the test failed if it does.
If you want to use a method to make it clearer as to what is being tested, you can write
public static void assertNoException(Object o) { }
assertNoException(driver.findElement(By.cssSelector(or.getProperty("addCustomerButton"))));
Upvotes: 3