How to mock exceptions using Mockito?

In the previous post I shared a sample program to mock exception conditions using JMockit. Today we will look into exception mocking with Mockito. As I mentioned in the earlier post, during the development time, testing an exception scenario without the help of the second party/third party service developer is not an easy task. However a mocking framework like Mockito will make things very simple for developers.

Complete source code used in this article can be cloned from github

package com.ourownjava.tdd.mockito.exception;

/**
 * 
 * @author Sanju Thomas
 *
 */
public interface DirtyWordService {
	
	public String getADirtyWord() throws DirtyWordsExhaustedException;
}

package com.ourownjava.tdd.mockito.exception;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class DirtyWordsExhaustedException extends Exception {

	private static final long serialVersionUID = 1L;

	public DirtyWordsExhaustedException(final String message){
		super(message);
	}
}
package com.ourownjava.tdd.mockito.exception;

public class ShoutingManager {

	private DirtyWordService dirtyWordService;
	
	public String getADirtyWord() throws DirtyWordsExhaustedException{
		return dirtyWordService.getADirtyWord();
	}

}

package com.ourownjava.tdd.mockito.exception;

import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * 
 * @author Sanju Thomas
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class TestShoutingManager {
	
	@InjectMocks
	private ShoutingManager shoutingManager;
	
	@Mock
	private DirtyWordService dirtyWordService;
	
	@Before
	public void setUp() throws DirtyWordsExhaustedException{
		when(dirtyWordService.getADirtyWord()).thenThrow(new DirtyWordsExhaustedException("To test the dirty words exhausted exception"));
	}
	
	@Test(expected = DirtyWordsExhaustedException.class)
	public void shouldGetDirtyWordsExhaustedException() throws DirtyWordsExhaustedException{
		shoutingManager.getADirtyWord();
	}

}


Leave a comment

Your email address will not be published. Required fields are marked *