Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use try-catch block with Assertions

This question is in mind for quite a long time and I want to know whether should I use try-catch Block with assertion or not? for example-

1. assertEquals(actual, expected);
2. try
{
assertEquals(actual, expected);
}
catch(AssertionError e)
{
e.printStackTrace();
}

What is the good practice? 1 or 2? TIA

like image 261
surendra Avatar asked May 19 '26 09:05

surendra


2 Answers

No, for sure you shouldn't do that. The purpose of the assertion is that when it fails, it throws the assertion error so the test unit engine is notified of that.

So, simply, do the assert. And make it working :). If it fails, you should solve the problem.

On the other hand, if what you want to test if that an exception is thrown. You can do it in several ways:

@Test(expected = NullPointerException.class)
public void myTestForException() {
    callMethodThatThrowsNullPointerException();
}

or you can use a try/catch:

@Test
public void myTest() {
    try {
        fail("Should throw whatever");
    } catch (MyException e) {
        // Everything is fine, test passed
    }
}
like image 192
Eduardo Yáñez Parareda Avatar answered May 20 '26 23:05

Eduardo Yáñez Parareda


The whole point of using JUnit, or TestNG, or something of that kind for your tests is that you can have thousands of tests in your project, and automate the testing. Running the tests can be part of the build process, and you get some feedback as to how many of the tests have passed. This is absolutely essential when your project consists of more than just a small handful of classes.

Your idea about catching the error that assertEquals throws and reporting it to the console is not a good one. Primarily because it makes the test pass when the assertion fails. That means that whatever you're using to run your tests (for example, Jenkins) is reporting the wrong result. You'll see, for example, that 5000 out of 5000 tests pass, even if a whole lot of them contain assertions that fail. And suddenly your large suite of tests has very little value.

Moreover, that stack trace that you so carefully print is going to get lost, in a flood of output from all the various tests.

So the short answer is that your idea (1) is the correct thing to do. It's what everyone does. And it means that the results of your tests are reported appropriately. You should never write tests like your idea (2).

like image 35
Dawood ibn Kareem Avatar answered May 20 '26 21:05

Dawood ibn Kareem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!