Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito, void method with checked exception

Tags:

java

mockito

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 .

like image 849
Aditya Kumar Avatar asked Oct 20 '13 08:10

Aditya Kumar


People also ask

How do you assert exception of void method in Mockito?

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.

How do I verify a void in Mockito?

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.


1 Answers

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.

like image 86
LaurentG Avatar answered Oct 19 '22 01:10

LaurentG