Mockito – cool mocking tool for Java

Mockito – cool mocking tool for Java

In a day to day TDD, one would happy in incorporating anything which would facilitate testing. Especially, on Object world, testing the interaction of objects on the method has been somehow rigorous.
Mockito is a handy tool in this regard. As the name suffice, it will mock objects and make them available for testing.
I will try to create a very simple situation where Mockito would show its power.
Let’s say we have an object named CityTemp – which would contain city and citie’s temperature. And let’s have another class named Forecast that would take CityTemp and would return simple string like city has high temperature or city has midium temperature or city has low temperature.

Say we want to test the Forecast part with different temperatures. The usual way would be instantiating CityTemp and filling it up with values. Unlike the usual way, Mockito has another approach.
Steps,
1. First download Mockito from Mockito site
2. Create a simple Java project and name it as you want.
3. Add the mockito jars to the project
4. Create the following two classes:
CityTemp

package mocklist;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 * 
 */
public interface ICityTemp {
	public String getCity();
	public void setCity(String city);
	public Double getTemperature();
	public void setTemperature(Double temperature);
}

package mocktest;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 * 
 */
public class CityTemp implements ICityTemp{
	private String city;
	private Double temperature;
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Double getTemperature() {
		return temperature;
	}
	public void setTemperature(Double temperature) {
		this.temperature = temperature;
	}
}

and
ForeCast

package mocktest;
/**
 * Class for forecasting.
 * @author Kaleb Woldearegay 
 *
 */
public class Forecast {
	private ICityTemp cityTemp;
	public Forecast(){
		
	}
	public Forecast(ICityTemp cityTemp){
		this.cityTemp=cityTemp;
	}
	public ICityTemp getCityTemp() {
		return cityTemp;
	}
	public void setCityTemp(ICityTemp cityTemp) {
		this.cityTemp = cityTemp;
	}
	
	/**
	 * Checks city's temperature and creates some verbiage
	 * @return String 
	 */
	public String weatherForcast(){
		String forecast=null;
		if (this.getCityTemp()!=null){
			if(this.getCityTemp().getTemperature() > 80){
				forecast=this.getCityTemp().getCity() + " has higher temp";
			}
			else if(this.getCityTemp().getTemperature() > 50){
				forecast=this.getCityTemp().getCity() + " has medium temp";
			}
			else{
				forecast=this.getCityTemp().getCity() + " has lower temp";
			}
		}
		return forecast;
	}
}

5. Now, we wanted to create a simple test to check forecast’s method
6. Create a test case file/class as follows:

import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import junit.framework.TestCase;
import mocktest.Forecast;
import mocktest.ICityTemp;
import static org.mockito.Mockito.when;

public class Another extends TestCase{
1	//mock the cityTemp object. with this simple annotation
2	@Mock private ICityTemp cityTemp;
3	public Another(){
4		MockitoAnnotations.initMocks(this);
5	}
6	@Test
7	public void testMidiumTemperature(){
8		Forecast forcast = new Forecast(cityTemp);
9		String expectedResult = "Addis Ababa has medium temp";
10		when(cityTemp.getTemperature()).thenReturn(65.0);
11		when(cityTemp.getCity()).thenReturn("Addis Ababa");
12		String actualResult = forcast.WeatherForcast();
13		assertEquals(expectedResult, actualResult);
	}
}

Let’s examine our lines of interest, in the test part.
Line two would be the one which starts the magic, it will create a mocked object of CityTemp. Look we don’t need to instantiate the object – it is mocked and we have it to manipulate as we want it.
That line can also be written as: private ICityTemp cityTemp = Mockito.mock(ICityTemp.class); In that case we might not need the statement at line 4.
At line 8, we passed the mocked object to the Forecast constructor. As you can see we haven’t needed the implementation of the interface when we pass it as argument – the mocked is enough by itself.
Then line 10 and 11 are the hearts of the mocking. Mockito would assign values as you wish! thats cool.
Line 10 says, whenever the CityTemp object is asked for temperature then return 65.0. Since the logic inside Forecast depends on temp value of CityTemp, we can vary as much as we want and get different values.
The same talk for line 12. The rest is, of course, history ….
Go thru http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html and enjoy..

See how you would solve these known algorithm problems

Array reversal in Recurrsion

Changing decimal number to its binary equivalent

Check if two strings are anagrams or not

Find the pairs that makes K Complementary in the given array java solution

String Ordered Permutation Algorithm Problem

Kadane’s algorithm in C – Dynamic Programming

Flatten nested javascript array

Implementing tokenizer and adding tokens to the linked list

Find K Complementary numbers from array Java implementation

Find the first occurence of number in the sorted array

10 Comments
  1. camilo lopes

    congrats, the best post i got to find about mocking. direct,objective and with good example, showing, mocking working very well.

    thanks for share your experience. i got to understand better, because of your post. :)
    see ya!

  2. vamsi

    good for starters…
    gives us a good understanding of what actually mocking is..

    1. gullele

      Thanks Vamsi, thank you.

  3. sathya

    Thanks for great post :)

    Now i got crux of mockito

  4. ajaxml

    cool tutorial!!
    No heavy weighted example like the other sites had!! Really good! Keep up the good work!

    1. gullele

      Thank you!

  5. debub

    The best tutorial on the topic I could find on the net! Just kept KISS :-)
    Thanks bro, you saved my day!

    1. gullele

      Thanks Debub.

  6. Spring Developer

    Nice article about Mockito, but the code formatting in the examples is awful. Try to use special WP plugins for this purpose

    1. gullele

      I will take a look at it regarding the formatting. Thanks for commenting.

Leave a Reply to gullele Cancel reply

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

*
*