Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - TestNG : Is It Wrong to use testng Assert.fail() in a catch block

I came across a code written by someone with Assert.fail("some text") in a catch block. This is my code:

try {
  //WebDriver code here which interacts with WebElements
  //When an exception occurs in this try block, it will be caught in 
  //the catch and further catch block has Assert.fail()
} catch (Exception e) {
    Assert.fail("failed to click 'Webelement' ");
}

I somehow felt this is not right way to do it. Am i wrong?

Note: Not exactly a duplicate of Is Assert.Fail() considered bad practice , As i am not expecting any Exception. If any exception occurs i need to fail the test case

like image 203
user2048204 Avatar asked Oct 26 '25 01:10

user2048204


1 Answers

Though it's syntactically not incorrect. But you should preferably rephrase your tests to use expectedException instead and be specific about the exception is thrown as well. For e.g. :

If your method fromTest() when called with "test" as an argument could throw an NumberFormatException, then your test definition for such behaviour should be :

@Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
    System.out.println("About to throw an exception!");
    fromTest("test");
}

Note: If you believe that the exception may so happen within your test execution itself instead of any other method being called from it. I would suggest to not catch it. Let it fail and then you shall fix it.

like image 87
Naman Avatar answered Oct 28 '25 15:10

Naman