I want to know why i need to handle exception ,when i am mocking a void method which throws exception.
For example
public class MyObject {
public void call() throws SomeException {
//do something
}
}
Now when i am doing this,
@Mock
MyObject myObject;
doNothing().when(myObject).call()
it results in compilation error saying
"error: unreported exception SomeException; must be caught or declared to be thrown"
I am wondering , why i need to handle exception for the method, which is itself being mocked .
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
Using the verify() Method Mockito provides us with a verify() method that lets us verify whether the mock void method is being called or not. It lets us check the number of methods invocations. So, if the method invocation returns to be zero, we would know that our mock method is not being called.
When you mock an object using Mockito in Java. The framework doesn't change anything to the language specification. And in Java, the throws
clause is defined at the compilation. You can't change the declared exceptions at runtime. In your case, if you call the method MyObject.call()
, you have to handle the SomeException
as in any normal Java code.
Since in unit test, you don't want to handle with things you are not testing. In your case, I would simply redeclare throws SomeException
in the test method.
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