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 ?
SchedulerExceptiondoes notextends RuntimeException? In this case, your test-method has to declarethrows SchedulerExcpetion. There is no other way to achieve what you want since Java enforces the catch-or-throws principle. the only exception (pun) to this areRuntimeExceptions (because nobody really wants to enclose each and every array-access in a try-catch-block...)@Test (expected = SchedulerException.class)if the above is the case.throws SchedulerExceptiontotestExample(you don't need to put it if your exception extendsRuntimeException): the test will fail in case of throwing the exception. If the purpose of the test is to test that the exception is thrown, you would you use try-catch, but I guess it is not your case.