We will start with the concept of Mocking. Mock in the basic terms means to imitate or to mimic. So, “mock” can therefore be thought of as a stand-in, an imposter or as most commonly referred to as it pertains to software development, a fake. Fakes are often used as stand-ins for dependencies of the class under test. Before proceeding, we need to understand two basic terms. They are as follows:
Now we need to know the use of mock. When we learn to program, our objects are usually self-contained. Any “hello world” has no dependencies on outside classes and neither do many of the other classes we write in the process of learning a language. However, in the real world, software has dependencies. We have action classes that depend on services and services that depend on data access objects and the list goes on. The idea of unit testing is that we want to test our code without testing the dependencies. This test allows the user to verify that the code being tested works, regardless of its dependencies. The concept behind mock objects is that we want to create an object that will take the place of the real object. This mock object will expect a certain method to be called with certain parameters and when that happens, it will return an expected result. Now, we will learn about some of the concepts of mocking. Some of them are stubbing, setting expectations and verifying. Let us learn about them in detail:
Now, after learning about the key concepts of mocking. Now, it’s time to learn about the benefits of mocking. They are as follows:
Now, after learning about mock in detail. Let us go through the Mockito Framework. Mockito is an open source testing framework for Java released under the MIT License.
Mockito distinguishes itself from other mocking frameworks by allowing developers to verify the behavior of the system under test (SUT) without establishing expectations beforehand. One of the criticisms of mock objects is that there is a tighter coupling of the test code to the system under test. Since Mockito attempts to eliminate the expect-run-verify pattern by removing the specification of expectations, the coupling is reduced or minimized. The result of this distinguishing feature is simpler test code that should be easier to read and modify.
Listing 1: Shows the code for mock creation
// mock creation
List mockedList = mock(List.class);
<span class="Apple-tab-span" style="white-space: pre;">
</span>// using mock object
mockedList.add("one");
mockedList.clear();
// selective and explicit vertification
verify(mockedList).add("one");
verify(mockedList).clear();
Listing 2: Shows the code for stub method calls
LinkedList mockedList = mock(LinkedList.class);
<span class="Apple-tab-span" style="white-space: pre;">
</span>// stubbing - before execution
when(mockedList.get(0)).thenReturn("first");
<span class="Apple-tab-span" style="white-space: pre;">
</span>// following prints "first"
System.out.println(mockedList.get(0));
<span class="Apple-tab-span" style="white-space: pre;">
</span>// following prints "null" because get(999) was not stubbed.
System.out.println(mockedList.get(999));
Now, let us go through a simple example of JAVA code in which Mockito is used.

Figure 1: Shows the image of database without Mock framework

Figure 2: Shows the image of the database with Mockito framework
Now there are three steps that are needed to be done. In the first step, create a Maven project in Eclipse.
Listing 3: Shows the code for defining pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<pre><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>vn.com.phatbeo.ut.mockito.demo</groupId>
<artifactId>demoMockito</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demoMockito</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
In the second step, JAVA source code is added.
Listing 4: Shows the code for class person.java
<?xml version="1.0" encoding="UTF-8"?>
<pre><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>vn.com.phatbeo.ut.mockito.demo</groupId>
<artifactId>demoMockito</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demoMockito</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
</dependencies> package vn.com.enclave.phatbeo.ut.mockito.demo;
/**
* @author Phat (Phillip) H. VU <vuhongphat@hotmail.com>
*
*/
public class Person
{
private final Integer personID;
private final String personName;
public Person( Integer personID, String personName )
{
this.personID = personID;
this.personName = personName;
}
public Integer getPersonID()
{
return personID;
}
public String getPersonName()
{
return personName;
}
}
Listing 5: Shows the code for interface PersonDAo0.java
package vn.com.enclave.phatbeo.ut.mockito.demo;
/**
* @author Phat (Phillip) H. VU <vuhongphat@hotmail.com>
*
*/
public interface PersonDao
{
public Person fetchPerson( Integer personID );
public void update( Person person );
}Listing 6: Shows the code for class PpersonSservice.java
package vn.com.enclave.phatbeo.ut.mockito.demo;
/**
* @author Phat (Phillip) H. VU <vuhongphat@hotmail.com>
*
*/
public class PersonService
{
private final PersonDao personDao;
public PersonService( PersonDao personDao )
{
this.personDao = personDao;
}
public boolean update( Integer personId, String name )
{
Person person = personDao.fetchPerson( personId );
if( person != null )
{
Person updatedPerson = new Person( person.getPersonID(), name );
personDao.update( updatedPerson );
return true;
}
else
{
return false;
}
}
}In the last step, unit test classes are added. In this step, we will be writing unit test cases for class PersonService.java
Listing 7: Shows the code for PersonServiceTest.java
package vn.com.enclave.phatbeo.ut.mockito.demo.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* @author Phat (Phillip) H. VU <vuhongphat@hotmail.com>
*
*/
public class PersonServiceTest
{
@Mock
private PersonDao personDAO;
private PersonService personService;
@Before
public void setUp()
throws Exception
{
MockitoAnnotations.initMocks( this );
personService = new PersonService( personDAO );
}
@Test
public void shouldUpdatePersonName()
{
Person person = new Person( 1, "Phillip" );
when( personDAO.fetchPerson( 1 ) ).thenReturn( person );
boolean updated = personService.update( 1, "David" );
assertTrue( updated );
verify( personDAO ).fetchPerson( 1 );
ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass( Person.class );
verify( personDAO ).update( personCaptor.capture() );
Person updatedPerson = personCaptor.getValue();
assertEquals( "David", updatedPerson.getPersonName() );
// asserts that during the test, there are no other calls to the mock object.
verifyNoMoreInteractions( personDAO );
}
@Test
public void shouldNotUpdateIfPersonNotFound()
{
when( personDAO.fetchPerson( 1 ) ).thenReturn( null );
boolean updated = personService.update( 1, "David" );
assertFalse( updated );
verify( personDAO ).fetchPerson( 1 );
verifyZeroInteractions( personDAO );
verifyNoMoreInteractions( personDAO );
}
}So, in this article, we have learnt about the basics of Mockito, its key concepts and benefits. We have also leant about its use in JAVA development .








See the prices for this post in Mr.Bool Credits System below: