Table of contents
1.
Introduction 
2.
BDD
3.
Setup
4.
Mockito VS BDDMockito
5.
BDD example
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Mockito BDD

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. A BDDMockito class is included with the Mockito library, introducing BDD-friendly APIs. We'll go over how to set up our BDD-based Mockito tests in this article. We'll also discuss the differences between the Mockito and BDDMockito APIs, focusing on the BDDMockito API in the end. So let’s dive into it!

BDD

Behavior Driven Development (BDD) encourages the use of natural, human-readable language when writing tests that focus on the application's behaviour.

The BDD syntax is divided into three sections:

  • Given: We can make use of the setup section and the syntax that has been provided.
  • When: We can perform the test's actual invocations.
  • Then: We can check whether the post-conditions are satisfied or not using readable asserts like assertThat().

Class BDDMockito

java.lang.Object
	org.mockito.BDDMockito
		org.mockito.Mockito
			org.mockito.BDDMockito

Setup

Maven Dependencies: Mockito's BDD flavour is included in the mockito-core library, so all we need to do is include the artefact:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.21.0</version>
</dependency>

Imports: If we add the following static import to our tests, they will become more readable:

import static org.mockito.BDDMockito.*;

Mockito VS BDDMockito

Mockito's traditional mocking is done with when(obj).then*() in the Arrange step.

Later, in the Assert step, we can use verify() to validate interaction with our mock.

Because BDDMockito provides BDD aliases for various Mockito methods, we can write our Arrange step with given (rather than when), and our Assert step with then (instead of verify).

Consider the following example of a test body created with traditional Mockito:

when(phoneBookRepository.contains(momContactName))
  .thenReturn(false);
 
phoneBookService.register(momContactName, momPhoneNumber);
 
verify(phoneBookRepository)
  .insert(momContactName, momPhoneNumber);


Let's see how it stacks up against BDDMockito:

given(phoneBookRepository.contains(momContactName))
  .willReturn(false);
 
phoneBookService.register(momContactName, momPhoneNumber);
 
then(phoneBookRepository)
  .should()
  .insert(momContactName, momPhoneNumber);

BDD 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.BDDMockito.*;


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 testAdd(){


      //Given
      given(calcService.add(20.0,10.0)).willReturn(30.0);


      //when
      double result = calcService.add(20.0,10.0);


      //then
      Assert.assertEquals(result,30.0,0);   
   }
}


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

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


Compile the classes using javac compiler to verify the result:

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


To see the result, run the Test Runner.

C:\Mockito_WORKSPACE>java TestRunner


Verify the output.

true

FAQs

  1. What is <T> given(T methodCall)?
    It's very similar to the method when(TmethodCall). It allows for stubbing.
  2. What is <T> then(T mock)?
    It enables mock behaviour verification in the BDD style.
  3. What is BDDStubber will(Answer<?> answer)?
    It's similar to the method doAnswer(Answer answer). When we want to stub a void method with the generic Answer, we use this.
  4. What is BDDStubber willReturn(Object toBeReturned)?
    It's similar to the doReturn(Object toBeReturned) method in that it returns an object. It's used in place of when you don't know what to say (Object).
  5. What is BDDStubber willThrow(Class<? extends Throwable> toBeThrown)?
    It works in the same way as the doThrow(Class<? extends Throwable> toBeThrown) method. When we want to stub a void method with an exception, we use it.

Key Takeaways

In this article, we have extensively discussed the theoretical and practical implementation of Mockito BDD.
We hope that this blog has helped you enhance your knowledge regarding the theoretical and practical implementation of Mockito BDD 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