Mockito - 2 minute tutorial

How to stub method to throw exception

A mocked object can also be asked to throw an exception when particular methods are called on it.

In the example below, the mock object is stubbed to throw NullPointerException when the method get(..) is called on it in line no. 14. The method used for this is thenThrow(..) of class org.mockito.Mockito.

If we need to throws exception when a method whose return type is void is called (eg. List.clear()), then we can use the alternate way of throwing exception , i.e. doThrow(..) of class org.mockito.Mockito as shown in line no. 15.