How to mock dependencies using Mockito?

In today’s post I would share a sample program that mock dependencies of the unit under test using Mockito. Mockito is the most simple mocking framework I ever used for java. Mockito is annotation driven and the APIs perfectly written so that you don’t even have to open the API documents to understand it.

The complete source code used in the article can be cloned from github

Mockito Annotations used in this article

Name Description
@RunWith To initialize the mocks; No need to use the MockitoAnnotations.initMocks(java.lang.Object) if you annot the class with @RunWith(MockitoJUnitRunner.class).
@Mock Create a mock object for the given type.
@InjectMocks Create an instance of the given type and inject all mocks into the given reference.
package com.ourownjava.tdd.mockito;
/**
 * @author Sanju Thomas
 *
 */
public class ShoutingManager {
	private DirtyWordService dirtyWordService;
	/**
	 * 
	 * @return
	 */
	public String shout(){
		return dirtyWordService.getADirtyWord();
	}
}

package com.ourownjava.tdd.mockito;

import java.util.Random;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class DirtyWordService {
	private static String [] dirtyWords = new String [] {"@#$#$", "F@#$#@$", "S@#$#$", "@#$#$#24", "@#$#$^#!@#"};

	public String getADirtyWord() {
		return dirtyWords[randomNumber()];
	}
	
	private int randomNumber() {
	    return new Random().nextInt((4 - 0) + 1) + 0;
	}
}

package com.ourownjava.tdd.mockito;

import static org.junit.Assert.assertEquals;
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 {
	@Mock
	private DirtyWordService dirtyWordService;
	@InjectMocks
	private ShoutingManager shoutingManager;
	
	//we are mocking the dirtyWordService of the shoutingManager
	//whenever getADirtyWord() method is called on dirtyWordService 
	//it will now return "You are such a nice person" 
	//We are smart developers..The dump manager will now start talking good words.
	@Before
	public void setUp(){
		when(dirtyWordService.getADirtyWord()).thenReturn("You are such a nice persion");
	}
	
	@Test
	public void shouldShout(){
		final String shout = shoutingManager.shout();
		assertEquals("You are such a nice persion", shout);
	}
}

Leave a comment

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