Can we handle Assert fail in try and catch in testNG

12k views Asked by At

I am trying to automate application using selenium webDriver + TestNG.

In which I am using multiple assert statement like Assert.assertEquals("Dhaval", "Dhaval1");

and I am trying to catch the assertionfail exception using try& catch block. as i am filling up an excell sheet for test result .

But any how while assertion fails application direct stop execution and catch block is will not execute.

Any suggestion.

Thanks in Advance!!!!

3

There are 3 answers

1
Mikhail On BEST ANSWER

Catching exceptions on test assertions is a bad practice, they are asserts for a reason. What you want to do is implement custom ITestListener and define required logic in onTestFailure(ITestResult result) method, code in this method will be executed if case will fail.

3
Ranjith's On

Try this:

try {
Assert.assertEquals("Dhaval", "Dhaval1");
}
catch (AssertionError e) {
Assert.assertEquals("Dhaval", "Dhaval");
}
0
lucrib On

If you are handling the tests results inside the test methods to save it to the spreadsheet, you are doing a bad practice. Take a look here to void this: http://www.techbeamers.com/save-selenium-webdriver-testng-result-excel/

Else, if you really need to do this:

try {
    Assert.assertNotEquals(actualValue, expectedValue);
} catch (Exception e) {
    // Thread the excpetion here
}