Sai Lakshmi
Sai Lakshmi

Reputation: 59

Mocking a method which throws exception

I have a method

Service.class

Public void foo() throws SchedulerException{

           ..........

}

Test.class

Public void testExample(){
     Mockito.doThrow(SchedulerException.class).when(f.foo());
 }

Compiler is asking me to put either a try/catch or throws for testExample() Is there any other way to achieve the same ?

Upvotes: 2

Views: 5338

Answers (1)

Turing85
Turing85

Reputation: 20185

Your question did not specify whether SchedulerException extends RuntimeException, but from your question I assume it does not.

Your test method (testExample()) has to throws SchedulerException if SchedulerException does not extends RuntimeException. This is due to Java's nature to enforce the catch-or-throws principle. The details can be found in JLS §11.

As was suggested by @Ishnark, if you expect your test to throw any kind of Exception, you should annotate the test with @Test(expected=ExcpectedExceptin.class) (even if your exception extends RuntimeExcpetion).

Upvotes: 1

Related Questions