Reputation: 297
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 .
Upvotes: 17
Views: 14480
Reputation: 1136
I was having a similar issue with multiple checked exceptions. My code looked something like this:
public class MyObject {
public void call() throws ExceptionOne, ExceptionTwo {
//do something
}
}
and my test was:
@Mock
MyObject myObject;
@Test
public void exampleTest throws ExceptionOne {
doThrow(new ExceptionOne()).when(myObject).call()
// assert...
}
the error message was unreported exception: ExceptionOne
The solution was to have exampleTest
throw both exceptionOne AND exceptionTwo. if you only report one checked exception it's not going to run.
Upvotes: 0
Reputation: 11757
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.
Upvotes: 18