Table of contents
1.
Introduction
2.
Reset Mock
3.
Mock Resetting Example
4.
Clear Invocations
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Resetting Mocks and clearing invocations

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

Introduction

Mockito is a JAVA-based mocking framework used for effective unit testing of JAVA applications. Mockito is a tool for mocking user interfaces so that dummy functionality can be added and used in unit testing. Mockito allows you to reset mocks and clear invocations. We will learn about Resetting Mocks and clearing invocations from this article, so let's dive in!

Reset Mock

Mockito allows you to reset a mock to be used again later. Take a look at the code snippet below.

//reset mock
reset(calcService);


We've reset the mock object in this case. MathApplication uses calcService, and using the mocked method after the mock has been reset will cause the test to fail.

Mock Resetting Example

Create a CalculatorService interface to provide mathematical functions.

CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}


To represent MathApplication, create a JAVA class.

MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

   public void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   public double add(double input1, double input2){
      return calcService.add(input1, input2); 
   }
   
   public double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   public double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   public double divide(double input1, double input2){
      return calcService.divide(input1, input2);
   }
}


Let's put the MathApplication class to the test by injecting a calculatorService mock into it. Mockito will be the one to create Mock.

MathApplicationTester.java

package com.tutorialspoint.mock;

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

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

// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {

   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = new MathApplication();
      calcService = mock(CalculatorService.class);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtract(){

      //add the behavior to add numbers
      when(calcService.add(20.0,10.0)).thenReturn(30.0);
  
      //test the add functionality
      Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);

      //reset the mock   
      reset(calcService);

      //test the add functionality after resetting the mock
      Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);   
   }
}


To execute Test case, create a java class file named TestRunner in C:\> Mockito_WORKSPACE (s).

TestRunner.java

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

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


Using the javac compiler, compile the classes as follows to verify the results:

C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.
   java MathApplicationTester.java TestRunner.java


To see the result, run the Test Runner again.

C:\Mockito_WORKSPACE>java TestRunner


Verify the output.

testAddAndSubtract(MathApplicationTester): expected:<0.0> but was:<30.0>
false

Clear Invocations

Mockito keeps track of method arguments and invocation count so that it can be asserted further, but we can clear all mocked instance invocations if necessary. Mockito has a Mockito#clearInvocations method. It is a contentious method that should be avoided unless you have a memory problem or cannot test efficiently. This feature should be avoided if possible. Only use this feature if you are unable to test the program effectively.

package com.example.mokito3.sujan;

public abstract class AppleService {
    public String saveApple(String apple) {
        String appleString = "i love " + apple + " apple";
        return appleString;
    }
}

 

package com.example.mokito3.sujan;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

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

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock
    private AppleService appleService;

    @Test
    void saveAppleWithMockTest() {
        when(appleService.saveApple("Macintosh")).thenReturn("i eat apple");
        appleService.saveApple("Macintosh");
        clearInvocations(appleService);
        verify(appleService).saveApple("Macintosh");
    }
}

 

plugins {
    id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

FAQs

  1. Is it appropriate to use Mockito.reset()?
    Smart Mockito users rarely use this feature because they are aware that it could indicate poor test results. Normally, you will not need to reset your mocks; instead, you will need to create new mocks for each test method. Instead of using reset(), consider writing short, focused test methods rather than lengthy, over-specified tests.
  2. What is Mockito when() method?
    It allows for the use of stubbing methods. When we want to mock to return specific values when certain methods are called, we should use it.
  3. What does mockitojunitrunner do?
    Mockitojunitrunner Detects unused stubs in the test code.
  4. What does verify method do in Mockito?
    The Mockito Verify methods are used to verify that a particular behaviour occurred. We can use Mockito verify methods at the end of the testing method code to ensure that specified methods are called.
  5. What does mock method in mockito do?
    We can create a mock object of a class or an interface using the Mockito. mock() method. The mock can then be used to stub return values for its methods and check whether they were called. This method does not require any further modifications before it can be used.

Key Takeaways

This article extensively discussed the theoretical and practical implementation of resetting mocks and clearing invocations.
We hope that this blog has helped you enhance your knowledge regarding the theoretical and practical implementation of resetting mocks and clearing invocations and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass