Tuesday 16 September 2014

Mockito Tutorial -Part1


  • What is Mockito?
    • Mockito is mocking frame work for Java Objects.
  • Why do we need to Mock Objects?
    • When an unit of code depended upon object that will not be available during test or development. We can create a mock object of it.
  • What is Mock Object?
    • A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls
Lets try to Mock a object of  Math class that was not avilable during development.

Math.java
package com.lac.tut.mockito;

/**
 * Performs various Math Operations like addition,multiplication and division ..etc 
 *
 */
public class Math {
 // addition of two numbers
 public int add(int a, int b) {
  return a + b;
 }

 // Multiply two numbers
 public int mul(int a, int b) {
  return a * b;
 }

 // Division of two numbers
 public int div(int a, int b) {
  return a / b;
 }
 
 //Return a prime number
 public int primeNumber(){
  return 5;
 }
}
Explanation: The above Math class has addition,multiplication,division as functions.

MathAddTestWithOutMock.java is a unit test cases that test add method on Math Object
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test the add method of Math object
 */
public class MathAddTestWithOutMock {
 Math mathObj; 

 @Before
 /**
  * Create Math object before you use them
  */
 public void create() {
  mathObj = new Math();//create a math object
 }

 @Test
 public void test() {
  assertSame(3, mathObj.add(1, 2)); // Assert that math object return 3
 }

}

Explanation: In the above example we try to test add method. Often In the Test Driven Development we will not have Math class before we write tests around it. The approach we have to take is Mock the Math object and write the tests using Mocked object.


MathMockAddTest.java Tests the add method of Math class by mocking Math Object
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test the add method of Math object
 */
public class MathMockAddTest {
 Math mathObj; //The object that needs to mocked
 
 @Before
 /**
  * Create mock object before you use them
  */
 public void create(){
  mathObj= mock(Math.class); //Create Math mock Object
  when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
 }
 
 @Test
 public void test() {
  assertSame(3, mathObj.add(1,2)); //Assert that math object return 3
 }

}

Explanation: In the above code the static method mock is going to create mock object of Math class. The static method when defines the behavior of add method. (i.e) When some one called add method with arguments 1 and 2 return 3 as output. Note: Please bear in mind. MathMockAddTest is never creating a Math concrete object it is only creating Math mock object.


MathMockAddTestWithAnnotation.java Creates a mock object with Mockito Annotations
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import com.lac.tut.mockito.Math;

/**
* Test the add method of Math object with  Mockito annotation
*/
public class MathMockAddTestWithAnnotation {
 @Mock
 Math mathObj;
 
 @Before
 /**
  * Create mock object before you use them
  */
 public void create(){
  initMocks(this);// Initialize this mock objects
  when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
 }
 
 @Test
 public void test() {
  assertSame(3, mathObj.add(1,2));//Assert that math object return 3
 }

}

Explanation:In the above example @Mock annotation is used to mock Math object. The static method initMocks initializes the mock objects in current class. Rest the behavior defined is same.


MathMockMulTest.java Test the multiplication method in Math class
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test multiply function
 */
public class MathMockMulTest {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class);
  when(mathObj.mul(anyInt(), eq(0))).thenReturn(0); //Multiply any number with zero. The function should return zero
 }
 
 @Test
 /**
  * Test the Multiply function in math object return zero if one of the argument is zero
  */
 public void test() {
  assertSame(mathObj.mul(1,0),0);
  assertSame(mathObj.mul(3,0),0);
 }

}

Explanation:In the above example the static method anyInt accepts any argument as input and static method eq checks that the argument is zero.


MathMockDivTestWithException test the exception returned by div method in Math class.
 
package test.com.lac.tut.mockito;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test division method of Math class
 */
public class MathMockDivTestWithException {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class); //Create Math Object
  when(mathObj.div(anyInt(), eq(0))).thenThrow(new ArithmeticException()); // Configure it to return exception when denominator is zero
 }
 
 @Test(expected=ArithmeticException.class) //expect the method throws ArithmeticException
 public void test() {
  mathObj.div(1,0); //call the div and expect to return ArithmeticException
 }

}

Explanation: The static method thenThrow should throw exception when denominator is zero.


MathMockPrimeNumTestWhichIsAMethodWithOutParameters Test a primeNumber method that doesn't take any argument
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

//Test a method that doesn't take any argument
public class MathMockPrimeNumTestWhichIsAMethodWithOutParameters{
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class); //Create Math Object
  when(mathObj.primeNumber()).thenReturn(5); // Configure it to return 5 as prime number
 }
 
 @Test
 public void test() {
  assertSame(5, mathObj.primeNumber());
 }

}
Explanation: In the above example when method primeNumber() is called the mock object will return 5


MathMockVerfiyTest Some times it is important to verify whether certain method on the object is called or called how many times. In such case we can use static method verify
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;


public class MathMockVerfiyTest {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class);
  when(mathObj.add(1,2)).thenReturn(3); 
 }
 
 @Test
 public void test() {
  //call the add function with 1,2 as arguments
  assertSame(mathObj.add(1,2),3);
  
  //Verify whether add method is tested with arguments 1,2 
  verify(mathObj).add(eq(1), eq(2));
  
  //Verify whether add method is called only once
  verify(mathObj,times(1)).add(1,2);
 }

}
Explanation: In the above example we try to assert that add method is called with arguments 1,2 and it is called only once. That can be achieved using verify method.


Download the source code of the above tutorial at http://www.luckyacademy.com/downloads.html



2 comments: