Table of contents
1.
Introduction
2.
Using Mockito.mock()
2.1.
Step 1 − Create an interface called Calculator to provide mathematical functions
2.2.
Step 2 − Create a JAVA class to represent mathApp
2.3.
Step 3 − Test the mathApp class.
2.4.
Step 4 − Execute test cases
2.5.
Step 5 − Verify the Result
3.
Benefits of Mockito
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Creating Mocks and need of mocking

Author Parth Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Mocking is a technique that allows testing of a class’s functionality in total isolation. Additionally, Mocking does not require property file read, file server read, or even a database connection to test the functionality.
Mockito makes creating mock objects straightforward as it uses Java Reflection to create mock objects for an interface.
This blog focuses on helping you understand how to create a mock. 

Using Mockito.mock()

The Mockito.mock() method enables us to create a mock object of a class or an interface.
We can then use the mock to return values for its methods and verify if they were called.
Mock objects. mock() creates mocks without bothering about the order of the method calls that mock is going to make while in action.

Step 1 − Create an interface called Calculator to provide mathematical functions

File: Calculator.java

public interface Calculator {
   public double add(double inp1, double inp2);
   public double subtract(double inp1, double inp2);
   public double multiply(double inp1, double inp2);
   public double divide(double inp1, double inp2);
}

Step 2 − Create a JAVA class to represent mathApp

File: mathApp.java

public class mathApp {
   private Calculator calc;


   public void setCalculator(Calculator calc){
      this.calc = calc;
   }
   
   public double add(double inp1, double inp2){
      return calc.add(inp1, inp2); 
   }
   
   public double subtract(double inp1, double inp2){
      return calc.subtract(inp1, inp2);
   }
   
   public double multiply(double inp1, double inp2){
      return calc.multiply(inp1, inp2);
   }
   
   public double divide(double inp1, double inp2){
      return calc.divide(inp1, inp2);
   }
}

Step 3 − Test the mathApp class.

Let's test the mathApp class by injecting a mock of Calculator in it. Mockito will create a mock.
Here we have appended two mock method calls, add() and subtract(), to the mock object via when(). However, we've called subtract() during testing before we call add(). When a mock object is made using create(), the order of execution does not matter.

File: MathsAppSection .java

package com.tutorialspoint.mock;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

// @RunWith will attach a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathsAppSection  {
   private mathApp mathApp;
   private Calculator calc;

   @Before
   public void setUp(){
      mathApp = new mathApp();
      calc = mock(Calculator.class);
      mathApp.setCalculator(calc);
   }

   @Test
   public void testAddAndSubtract(){

      //adding the behavior to add numbers
      when(calc.add(20.0,10.0)).thenReturn(30.0);

      //subtracting the behavior to subtract numbers
      when(calc.subtract(20.0,10.0)).thenReturn(10.0);

      //testing the subtract functionality
      Assert.assertEquals(mathApp.subtract(20.0, 10.0),10.0,0);

      //testing the add functionality
      Assert.assertEquals(mathApp.add(20.0, 10.0),30.0,0);

      //verifying call to calc is made or not
      verify(calc).add(20.0,10.0);
      verify(calc).subtract(20.0,10.0);
   }
}

Step 4 − Execute test cases

Next we create a java class file called RunTest in C:\> Mockito_WORKSPACE to execute Test case(s).

File: RunTest.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class RunTest {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathsAppSection .class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
} 

Step 5 − Verify the Result

Compile the classes using the javac compiler.

C:\Mockito_WORKSPACE>javac Calculator.java mathApp.java MathsAppSection .java RunTest.java

Now run the Test Runner to get the result.

C:\Mockito_WORKSPACE>java RunTest

Verify the output.

true

Benefits of Mockito

  • No Handwriting − There is no need to program mock objects independently.
  • Easy Refactoring− Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime.
  • Return support − Supports return values.
  • Exception support − Supports exceptions.
  • Order check support − Supports check on the order of method calls.
  • Annotation support − Supports creating mocks using annotations.

FAQs

  1. What is Mocking?
    Mocking is a technique that allows testing of a class’s functionality in total isolation. Additionally, Mocking does not require property file read, file server read, or even a database connection to test the functionality.
  2. When should you mock a class?
    Mock objects are helpful for testing interactions between a class under test and a particular interface.
  3. What does mock in Mockito do?
    The Mockito. mock() method enables us to create a mock object of a class. We can then use the mock to stub return values for its methods and verify if they were called.
  4. What are the reasons to use mock objects in unit tests?
    In a unit test, mock objects can assume the behavior of complex and real objects. They are extremely helpful when a real object is impractical or impossible to incorporate into a unit test.
  5. What is a mocking framework?
    A mocking framework is required to create replacement objects. These objects can be Stubs, Fakes, or Mocks. In a unit testing scenario, programmers use mocking frameworks to isolate the dependencies. This allows for a quick and reliable way to ensure smooth testing.

Key Takeaways

In this article, we have extensively discussed how to create a mock and the need for mocking in the first place. If you are Preparing for interview and don't know where to start, we have got you covered, check out our expert curated courses on our website, You can also check out Coding Ninjas Studio to practice frequently asked interview problems. We hope that this blog has helped you enhance your knowledge regarding Mockito and if you would like to learn more, check out our articles. Do upvote our blog to help other ninjas grow. Happy Coding!”

Live masterclass