17
votes

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 .

2
You don't need to handle it. Just put throws Exception on your test method. I mark all my JUnit methods with throws Exception as a matter of habit - there's no reason not to.Dawood ibn Kareem
@DawoodibnKareem When I want to signal that a test is supposed to throw exceptions I use assertion helpers, as for example @Test(expected = ...). I try to avoid the throws clause in the test method signature as it does not had any useful information about the test itself.José Andias

2 Answers

17
votes

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.

0
votes

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.