Templates by BIGtheme NET

Mockito Quick Start

In this Article, I will give you brief introduction about Mockito.
Simple program that helps to understands mockito stubbing.

What is Mockito ?

1) An open source testing framework for Java.

2) The framework allows the creation of mock objects in
automated unit tests for the purpose of Test-driven Development (TDD)
or Behavior Driven Development (BDD).

Tools Uses :

1) mockito – 2.0.29-beta
2) eclipse version Luna 4.4.1.
3) Maven 3.3.3
4) JDK 1.6

Simple “Hello wold” program to use Mockito.

Simple Steps to follow,

1) Create a maven project.
2) Add mockito dependency to pom.xml file
3) Write a simple program that using Mockito framework.
4) Demo, run and verify the out put

Dependency that need to be added to pom.xml file is,


	org.mockito
	mockito-core
	2.0.28-beta

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.devjavasource.mokito</groupId>
  <artifactId>BasicExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>BasicExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>org.mockito</groupId>
	    <artifactId>mockito-core</artifactId>
	    <version>2.0.28-beta</version>
	</dependency>
  </dependencies>
</project>

Write a simple program that using Mockito framework :

1) import Mockito statically.

import static org.mockito.Mockito.*;

2) Creating a mock object.

Using mock() method, we can create a mock object.
we need to pass the object to the mock() method.

// How to create a mock object on user defined entities.
Bank mockedBank = mock(Bank.class);

// How to create a mock object on java pre-defined classes.
LinkedList mockedList = mock(LinkedList.class);

3) Stubbing the mock object.
We can stubbing the mock object using “when” and “thenReturn”.

// stubbing appears before the actual execution
when( mockedList.get(0)).thenReturn(bank);
// If we try to get second element in list, throws RuntimeException
when( mockedList.get(1)).thenThrow(new RuntimeException());

// This returns bank object, that we stubbed in previous step for index 0
System.out.println("Bank Object is:" + mockedList.get(0) );

4) Verify the mock object.
we can use verify() method to verify the results.

verify(mockedBank).add(bank);

Here are java source code,
App.java

package com.devjavasource.mokito.BasicExample;

import static org.mockito.Mockito.*;

import java.util.LinkedList;

public class App
{
    
	public static void main( String[] args )
    {      
		// Once created, mock will remember all interactions. 
		new App().useCase1();
		
		// How to do stubbing
		new App().useCase2();
    }
	
	private void useCase2(){
		
		Bank bank = new Bank(101,"OAK","WELLS FORGO");		
		
		LinkedList mockedList = mock(LinkedList.class);		
		
		// stubbing appears before the actual execution
		when( mockedList.get(0)).thenReturn(bank);
		// If we try to get second element in list, throws RuntimeException
		when( mockedList.get(1)).thenThrow(new RuntimeException());
		
		// This returns bank object, that we stubbed in previous step for index 0
		System.out.println("\nBank Object is:" + mockedList.get(0) );

		// This returns null, because, no stubbing for index 999 
		System.out.println(mockedList.get(999));
	}
	
	private void useCase1(){
		
	    Bank bank = new Bank(101,"OAK","WELLS FORGO");
	    
	  //Create a mock object
	    Bank mockedBank = mock(Bank.class);
	    
	    //using mock object
	    mockedBank.add(bank);        
	    mockedBank.clear();
	    System.out.println("mockedBank list is: " + mockedBank.get());
	    
	    //Even we clear the list also, but mock will remember all the interactions.
	    //verification
	    verify(mockedBank).add(bank);
	    verify(mockedBank).clear();
	    
	    System.out.println("mockedBank list is: " + mockedBank.get());
	    
	  //Create a mock object
	   Bank bank1 = new Bank(101,"OAK","WELLS FORGO");
	   //verify(mockedBank).add(bank1); // This will throw an error
	}
}

Entity bean class is,
Bank.java

package com.devjavasource.mokito.BasicExample;

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

public class Bank {

	private int bankId;
	private String bankAddress;
	private String bankName;
	
	private List bankList = null;
	
	Bank(int inBankId, String inBankAddress, String inBankName){
		bankId = inBankId;
		bankAddress = inBankAddress;
		bankName = inBankName;
	}
	
	public void add(final Bank inBank){
		if(bankList == null){
			bankList = new ArrayList();
		}
	}
	
	public void clear(){
		if(bankList != null) bankList.clear();
	}
	
	public List get(){
		return bankList;
	}

	public int getBankId() {
		return bankId;
	}

	public String getBankAddress() {
		return bankAddress;
	}

	public String getBankName() {
		return bankName;
	}
	
}

Demo :
Select App.java and “Run As” -> “Java Application”

Out Put:

mockedBank list is: []
mockedBank list is: []

Bank Object is:com.devjavasource.mokito.BasicExample.Bank@14d3bc22
null

You can download complete project, Here
BasicMockitoExample

*** Venkat – Happy leaning ****