2 Minutes To Code (β Version)

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.
package com.techfundaes.mockitoBag;

import static org.mockito.Mockito.*;

import java.util.ArrayList;
import java.util.List;

public class ThrowException
	public static void main(String[] args)
		List myMockedList = mock(ArrayList.class);
		when(myMockedList.get(anyInt())).thenThrow(new NullPointerException());
		doThrow(new RuntimeException()).when(myMockedList).clear();