The main aspect of unit tests is to help you isolate / resolve errors in your production code as quickly as possible.
In this sense: you are not writing your @Test methods to be called by other methods. You write them so that they are executed by the JUnit framework.
And usually when this test throws an exception; it makes no sense to catch this (if it is not expected, and you want to continue checking this exception).
Thus: not having catch blocks; and instead, adding the potential causes of the drop to your test method signatures is the correct answer in 99.999% of all cases. Or maybe 100%; since I cannot find a good counter example.
But I would be careful if I quickly used throws Exception . You still want your code as specific as possible; so itβs better to go for throws ThatExceptionThatCanReallyBeThrown . And when this list is too long too often ... then you better keep an eye on this side and check if your cast list in your production code needs to be βcut offβ in some way.
Edit: perhaps the main thing to understand: for each of your tests, you have the expected exactness of what will happen. This method should:
- Do not throw an exception
- Throw a specific exception (then you will do the
@Test(expected=...) thing - Throw a specific exception ... that your test needs to be caught for further verification.
- Throw an exception ... which will then point to the real βerrorβ condition (because you did not expect this); and in this case, JUnit will catch the exception and report it to you as an unsuccessful test file. (But of course, keep in mind that there is a subtle difference in JUnit with a test error and a test error.)
And just putting throws X, Y on your test method signature is a direct way to address bullets 2 and 4.
Ghostcat
source share