MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement Mockito framework in JAVA

In this article, we will be learning about some basic concepts of mocking framework. We will also walkthrough a simple example of its application in Java.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

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:

  • Dependency - A dependency is when one class in an application depends upon another in order to perform its intended function.
  • Dependencies are often stored in instance variables inside of the dependent class.
  • Class Under Test - When writing unit tests, the term “unit” generally refers to a single class and specifically the class against which the tests are written. The class under test is therefore the application class that is being tested.

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:

  • Stubbing: Stubbing is the process of telling your fake how to behave when it is interacted with. Users can generally stub public properties (those with getters and/or setters) and public functions. When it comes to stubbing functions, users have a lot of choices typically. Sometimes, users may wish to return a specific value, they can either throw an error or dispatch an event. Further, users may wish to indicate that the function behaves differently depending upon how it is invoked.
  • Setting Expectations: One of the key features of a fake is the ability to tell the fake what you expect when your test runs. For example, users may expect that a specific function be invoked exactly 3 times. They may expect that it never be invoked. Users may expect that it be invoked at least twice, but not more than 5 times. Users may expect that it be invoked with specific types of arguments or specific values or any combination of the above. The possibilities are endless. Setting expectations is the process of telling your fake what you expect to happen to it. Remember that since it’s a fake, nothing actually happens. But, your class under test is none the wiser. From its perspective, it invoked the function and expects that it did whatever it was supposed to do.
  • Verifying: This is the last concept of mocking. Setting expectations and verification go hand in hand. Setting expectations is done prior to invoking the function(s) on the class under test. Verification is done after. So, first you set expectations, and then users must verify that their expectations were met.

Now, after learning about the key concepts of mocking. Now, it’s time to learn about the benefits of mocking. They are as follows:

  • It allows us to create tests in advance also known as TDD. If you create a Mock you can write Service Tests before the service is created, giving you the ability to add the tests to your automation environment in the development process. In other words,
  • Service Mocking gives you the ability to use Test Driven Development.
  • It allows teams to work in parallel.
  • It also allows the users to create proof of concepts or demos.
  • Mock can also be delivered to the customer. It helps to isolate systems.

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.

Shows the image of database without Mock framework

Figure 1: Shows the image of database without Mock framework

Shows the image of the database with Mockito 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 );
    }
}

Conclusion

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 .



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

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

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login