java method! - Mockito test a void method throws an exception
checked only (3)
I have a method with a
void return type. It can also throw a number of exceptions so I'd like to test those exceptions being thrown. All attempts have failed with the same reason:
The method when(T) in the type Stubber is not applicable for the arguments (void)
Any ideas how I can get the method to throw a specified exception?
If you ever wondered how to do it using the new BDD style of Mockito:
The parentheses are badly placed. You must use
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...); ^
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...)); ^
This is explained in the documentation
Indeed, checked exceptions on the one hand increase robustness and correctness of your program (you're forced to make correct declarations of your interfaces -the exceptions a method throws are basically a special return type). On the other hand you face the problem that, since exceptions "bubble up", very often you need to change a whole lot of methods (all the callers, and the callers of the callers, and so on) when you change the exceptions one method throws.
Checked exceptions in Java do not solve the latter problem; C# and VB.NET throw out the baby with the bathwater.
In short, it allows you to say:
method g(x) throws like f(x), which means that g throws all the exceptions f throws. Voila, checked exceptions without the cascading changes problem.
Although it is an academic paper, I'd encourage you to read (parts of) it, as it does a good job of explaining what the benefits and downsides of checked exceptions are.