Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions in JUnit setup methods

Tags:

java

junit

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?

like image 392
Steve Avatar asked Dec 11 '12 01:12

Steve


1 Answers

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.

like image 114
VGR Avatar answered Sep 24 '22 08:09

VGR