Table of contents
1.
Introduction
2.
Setup
3.
Mockito Annotations
3.1.
@Mock
3.1.1.
Program
3.2.
@Spy
3.2.1.
Program
3.3.
@InjectMocks
3.3.1.
Program
4.
Math Application Example
4.1.
Program
4.2.
Program
4.3.
Program
4.4.
Output
5.
Frequently Asked Questions
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Mockito Integration in JUnit

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

Introduction

Mocking in unit testing is vital to isolate the application under test from external dependencies. So while performing unit testing in Java using one of the most popular testing frameworks for Java, JUnit, a developer will need to implement mocking. Mockito is a mocking framework for Java that simplifies automation testing for us. Because Mockito helps you create objects without dependencies on a test-specific configuration, it makes unit testing highly efficient with cleaner tests and improves the test independence of developing components. 

The most popular method of integrating Mockitio is integrating it with the JUnit testing framework. We will explore the Mockito-JUnit integration in Java with the help of examples in this article.

Setup

To integrate Mockito in JUnit, you must already have ample knowledge of working with JUnit to write tests. If you want to learn about JUnit, you can find required resources in articles like JUnit Introduction and FeaturesJUnit Environment Setup and Framework, and JUnit Test Suites.

There are two versions in which Mockito is available; mockito-core, which contains only the core modules of Mockito, and mockito-all, which has all of the modules. To start writing unit tests using Mockito in JUnit, you first need to install it in your Java project. One straightforward way of adding Mockito to your project is downloading the jar file and placing it in a path where your build system can find it. However, this is not the recommended method of installing Mockito.

The most preferred method of installing Mockito is by declaring a dependency on mockito-core using a build system of choice, like Maven or Gradle.

While working in a Maven project, you can add Mockito in the pom.xml file of your project like this:

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>4.1.0</version>
      <scope>test</scope>
    </dependency>

While using Gradle, you can achieve this by declaring the following dependency in your build.gradle file:

compile("org.mockito:mockito-core:4.1.0")

Mockito Annotations

Like JUnit, you can also integrate Mockito annotations to specify the test code behavior. These annotations make the integration of Mockito in JUnit seamless and easy to implement. The Mockito Annotations allow us to focus more on our logic while testing our code effectively.

Here we will discuss some of the most commonly used Mockito Annotations in JUnit.

@Mock

The purpose of the @Mock annotation is to create a mock object in our test. We always use the @Mock annotation with the JUnit @RunWith annotation, a class-level annotation in JUnit.

We will look at integrating both these annotations in the Math Application Example later in this article.

Program

@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
…..
   //We use the @Mock annotation to create the mock object to be injected
   @Mock
   CalculatorService calcService;
…..}
You can also try this code with Online Javascript Compiler
Run Code

@Spy

We create  Spy instead of a Mock for partial mocking in our test. A Spy's default behavior is to call the real implementation in all non-mocked methods. We use the @Spy annotation to create a spy or partial mock of an object. That helps us call all the object methods while tracking every mocked interaction. 

Below is an example of how you would implement a spy using Mockito in JUnit.

Program

    @Spy
    List<String> myList = new ArrayList<String>();
     
    @Test
    public void usingSpyAnnotation() {
       myList.add("Hello, This is ExampleTest");
       Mockito.verify(spyList).add("Hello, This is ExampleTest");
       assertEquals(1, spyList.size());
    }
You can also try this code with Online Javascript Compiler
Run Code

@InjectMocks

We can use the @InjectMocks class to mock an object with all its dependencies. This annotation is quite handy when you want to test a unit's behavior completely.

We will see the implementation of the @InjectMocks annotation extensively in the Math Application Example in the next section.

Program

public class MathApplicationTester {
…..  
 //We use @InjectMocks 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;
…..}
You can also try this code with Online Javascript Compiler
Run Code

Math Application Example

Now, we will implement the integration Mockito in JUnit with the help of an elementary example where we will test a Calculator Service interface using mocks.

We will start by creating 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 Javascript Compiler
Run Code

Next, we will create a Java class that implements our Calculator Service interface from above(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 Javascript Compiler
Run Code

Finally, we can test the above class by injecting a mock of our service interface using Mockito and JUnit. We will use the @Mock, @InjectMock, and @RunWith annotations in the test code below.

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 Javascript Compiler
Run Code

Output

Frequently Asked Questions

  1. Is Mockito part of JUnit?
    Mockito is a java based mocking framework. You can use Mockito in conjunction with other testing frameworks like JUnit and TestNG. Mockito allows us to create objects of service by using Java Reflection API.
     
  2. Why do we need Mockito in JUnit?We use Mockito to mock interfaces to add a dummy functionality to a mock interface that we can use in unit testing. The primary purpose of the Mockito framework is to simplify the development of a test by mocking external dependencies to use in the test code. Mockito provides you with a test code that is simpler, easy to read, understand, and modify.
     
  3. What are the benefits of using Mockito?
    The Mockito framework is full of features and tools that can benefit you while writing a unit test. Some of the key benefits of using Mockito are below.
    Supports the use of Annotations.
    Supports check on the order of method calls.
    Supports Exceptions.
    Supports return values.
    You don’t need to write mock objects on your own.
     
  4. What are the limitations of Mockito?
    There are some limitations of the Mockito are:
  • It can’t mock constructors or static methods.
  • It requires Java version 6 or higher run.
  • It also can’t mock equals() and hashCode() methods.

Conclusion

In this article, we have extensively discussed the integration of the Mockito framework with the JUnit testing framework and its implementation in unit testing using Java programming. Many more features and applications are possible with the Mockito-JUnit integration in Java. 

We hope this blog has helped you enhance your knowledge regarding mocking and unit testing in Java. If you would like to learn more, check out our articles on  JUnit Introduction and FeaturesJUnit Environment Setup and Framework, and Basics of Java. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass