Throw checked Exceptions from mocks with Mockito

I am trying to get one of my mocking objects to throw an exception when calling a particular method. I am trying to do the following.

@Test(expectedExceptions = SomeException.class) public void throwCheckedException() { List<String> list = mock(List.class); when(list.get(0)).thenThrow(new SomeException()); String test = list.get(0); } public class SomeException extends Exception { } 

However, this causes the following error.

 org.testng.TestException: Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Invalid: com.testing.MockitoCheckedExceptions$SomeException 

Looking at the Mockito documentation , they only use RuntimeException , is it impossible to throw checked Exceptions from the layout with Mockito?

+120
java mockito mocking
Sep 21 '10 at 15:50
source share
2 answers

Check out the Java API for a list . The get (int) method is declared to throw only an IndexOutOfBoundException, which extends a RuntimeException. You are trying to get Mockito to throw an exception that is not valid for this particular method call.

To clarify further. The List interface does not throw an exception for the get () method, so Mockito does not work. When you create a dummy list, Mockito uses the definition of List.class to create its layout. The behavior you specify with when(list.get(0)).thenThrow(new SomeException()) does not match the method signature in List.class, so Mockito fails. If you really want to do this, then let Mockito throw a new RuntimeException() or, even better, throw a new ArrayIndexOutOfBoundsException() as the API indicates that this is the only valid exception that will be thrown.

+163
Sep 21 '10 at 15:58
source share

The workaround is to use the willAnswer() method.

For example, the following works (and not a MockitoException but actually throws a validated Exception as required here) using BDDMockito :

 given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); }); 

Equivalent to a simple Mockito will use the doAnswer method

+49
Jan 15 '18 at 10:24
source share



All Articles