Instead of doing Exception-handling in my JUnit tests, I just declare my test-methods with ... throws Exception
?
I started doing that and I don't see a reason why I should be more specific.
The core aspect of unit-tests is to help you isolate / resolve bugs in your production code as quickly as possible.
In that sense: you do not write your @Test methods in order to be called by other methods. You write them so that the JUnit framework runs them.
And typically, when that test throws an exception; there is no point in catching that (unless it is expected; and you want to do further checking on that exception).
Thus: not having catch blocks; and instead adding potential throw causes to your test method signatures is the correct answer in 99.999% of all cases. Or maybe 100%; as I can't find a good counter example.
But I would be careful though about using throws Exception
to quickly. You still want your code to be as "specific" as possible; so better go for throws ThatExceptionThatCanReallyBeThrown
. And when that list grows too lengthy too often ... then you better follow up on that side and check if your throws list in your production code should be "trimmed" down somehow.
Edit: probably the core thing to understand is: for each any any of your tests, you have an exact expectation towards what will happen. That method should either:
@Test(expected=...)
thingAnd just putting throws X, Y
on your test method signature is the straight forward way of addressing bullets 2 and 4.
In addition to @GhostCat answer want to say -
JUnit has nice feature named Rules. It is well suited for testing exceptions and maybe better than @Test(expected=Whatever.class)
.
Example usage:
public class Test {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private MyService myService;
@Before
public void setUp() {
myService = new MyService ();
}
@Test
public void exceptionTest() throws MyException {
thrown.expect(MyException.class);
thrown.expectMessage("my description");
myService.create("bad argument"); //throws MyException("my description")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With