Table of contents
1.
Introduction
2.
Verifying Behavior
2.1.
Program
2.2.
Program
2.3.
Program
2.4.
Output
3.
Adding Behavior
3.1.
Program
3.2.
Output
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Testing Behavior With Mockito

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A developer spends a significant portion of the effort while designing hardware systems and applications on testing and verification. Behavior Driven Development(BDD), which is an extension of Test-Driven Development(TDD), is a development technique where acceptance tests are written in natural language to drive the implementation. You can learn more about TDD and BDD here.

We will learn to add and verify behavior using the when() and verify() methods available in the Mockito mocking framework in Java through this article with the help of concept explanations and examples.

Verifying Behavior

Mockito can ensure if a mock method is being called with required arguments or not using the verify() method. You can use the verify methods in Mockito at the end of a method code to make sure that specified methods are called. That essentially means that the verify methods check whether a particular behavior happened. 

To try out a straightforward implementation of the verify method, we will create an interface(CalculatorService) with arithmetic operations.

Program

//src/main/java/com.codingninjas.testrunner/CalculatorService.java
package com.codingninjas.testrunner;


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);
}

You can also try this code with Online Java Compiler
Run Code

We will now create a java class that implements the service from our interface(MathApplication).

Program

//src/main/java/com.codingninjas.testrunner/MathApplication.java
package com.codingninjas.testrunner;


public class MathApplication {
  private CalculatorService calcService;


  public void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
  }
   
  public double add(double input1, double input2){
      //returns calcService.add(input1, input2);
      return input1 + input2;
  }
   
  public double subtract(double input1, double input2){
 //returns calcService.subtract(input1, input2); 
      return calcService.subtract(input1, input2);
  }
   
  public double multiply(double input1, double input2){
 //returns calcService.multiply(input1, input2);  
      return calcService.multiply(input1, input2);
  }
   
  public double divide(double input1, double input2){
 //returns calcService.divide(input1, input2);  
      return calcService.divide(input1, input2);
  }
}
You can also try this code with Online Java Compiler
Run Code

Finally, we will test the above class by injecting a mock of our service interface using Mockito. We will use the verify method to verify the behavior of our interface.

Program

//src/test/java/com.codingninjas.testrunner/MathApplicationTest.java
package com.codingninjas.testrunner;


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


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


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

   //We use @InjectMocks annotation to create and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = new MathApplication();


   //We use @Mock annotation to create the mock object to be injected
   @Mock
   CalculatorService calcService;


   @Test
   public void testAdd(){
      //adds the behavior of CalcService for addition of two numbers
      when(calcService.add(10.0,20.0)).thenReturn(30.00);

      //tests the add functionality
      Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);
       
      //verifies the behavior
      verify(calcService).add(10.0, 20.0);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Adding Behavior

The when() method in Mockito enables stubbing methods. We can use the when method when we want the mock to return specific values when particular methods are called. In simpler terms, when a method x() is called, it should return a value y

To implement adding behavior with the when() method, we instructed Mockito to give a behavior of adding two numbers to the add method of our Service interface (calcService) in our previous test (MathApplicationTest) example and, as a result, to return a particular value.

We can also implement adding behavior without verifying in the same test suite.

Program

//src/test/java/com.codingninjas.testrunner/MathApplicationTest.java
package com.codingninjas.testrunner;


import static org.mockito.Mockito.when;


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


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

   //We use @InjectMocks annotation to create and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = new MathApplication();


   //We use @Mock annotation to create the mock object to be injected
   @Mock
   CalculatorService calcService;


   @Test
   public void testAdd(){
      //adds the behavior of CalcService for addition of two numbers
      when(calcService.add(10.0,20.0)).thenReturn(30.00);

      //tests the add functionality
      Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);
       
    
   }
}

You can also try this code with Online Java Compiler
Run Code

Output

Frequently Asked Questions

  1. How to verify a void method in Mockito?
    To verify a mock method in Mockito, you need to first perform the action under test and then call verify(). By using the verify() method, you will test that at some point, the method from the mock was called with the same parameters. 
     
  2. How to mock void method in mockito?
    We can implement different methods, mock void, or call a real method in Mockito. We can use one of the options like doNothing(), doAnswer(), doThrow(), or doCallRealMethod() as per the project requirement.
     
  3. Why do we need Mockito?
    The main objective of using the Mockito framework is to simplify the development of a test by mocking external dependencies and using them in the test code. As a result, Mockito provides a simpler test code that is easier to read, interpret, and modify.
     
  4. Can we mock static methods using Mockito?
    Mockito allows us to generate mock objects. However, there is no way in Mockito to mock static methods because the static method belongs to the class. But we can use PowerMock along with the Mockito framework to mock static methods.

Conclusion

In this article, we have extensively discussed verifying behavior and adding behavior using verify() and when() in the Mockito framework and their implementation in the JUnit testing framework. We have used both the methods of Behavior Driven Development through our test suite example in Java.

We hope that this blog has helped you enhance your knowledge regarding Testing Behavior using Mockito. Do upvote our blog to help other ninjas grow.

We have a lot more to learn in this domain. So be sure to check out our excellent introductory articles like JUnit Introduction and FeaturesJUnit Environment Setup and Framework, and Basics of Java. And head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Till then, Happy Learning!

 

Live masterclass