How to handle exceptions in JUnit setup methods
If your test class needs those files to perform its tests, then you should declare the @Before method with throws IOException
. That way, if the creation of the files fails, the test class will fail and the reason will be obvious from the exception. If you catch and suppress the IOException, the unit tests which need those files will likely fail anyway, and it will be in a way that will require detective work.
For the @After method, the stakes aren't as high. I would declare the @After method with throws IOException
just because it's easier to code and to read. You could probably catch the IOException without doing much harm, but then, shouldn't the cleanup always succeed? If that code can't clean up the files, something is weird about your environment and it's probably good to be aware of it. So that's another reason to add throws IOException
to the @After method.
Related videos on Youtube
Steve
Updated on September 16, 2022Comments
-
Steve over 1 year
I have a unit test case, which involves creating some files with random contents, then test using the files and as clean up, delete the files.
So I need to create files and write to files in @Before method. How should I handle exceptions?
-
Mel Nicholson over 11 yearsMost runners report this fine if you just let the exception out. If you actually plan to recover from the exception, good old try-catch is the way.
-
John B over 11 yearsIf you are not already using it, consider the TemporaryFolder Rule to help with the cleanup of these files.
-
-
John B over 11 yearsFYI, using the TemporaryFolder rule would negate the need for explicit cleanup in an After method