Table of contents
1.
Introduction
2.
Exception Handling-Example
2.1.
Step 1 − Creating interface CalculatorMain that provide mathematical functions
2.2.
Step 2 − Creating a class to represent MathApp
2.3.
Step 3 − Testing the MathApp class.
2.4.
Step 4 − Executing test cases.
2.5.
Step 5 − Verifying the Result
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Testing exceptions

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

Introduction

Mockito provides the functionality of a mock that throws exceptions. This allows us to perform exception handling.
This blog will help you understand Exception handling in Mockito with an example.

Exception Handling-Example

Step 1 − Creating interface CalculatorMain that provide mathematical functions

File: CalculatorMain.java

public interface CalculatorMain {
   public double add(double inp1, double inp2);
   public double subtraction(double inp1, double inp2);
   public double multiplication (double inp1, double inp2);
   public double division(double inp1, double inp2);
}

Step 2 − Creating a class to represent MathApp

File: MathApp.java

public class MathApp {
   private CalculatorMain calcService;


   public void setCalculatorMain(CalculatorMain calcService){
      this.calcService = calcService;
   }
   
   public double add(double inp1, double inp2){
      return calcService.add(inp1, inp2); 
   }
   
   public double subtraction(double inp1, double inp2){
      return calcService.subtraction(inp1, inp2);
   }
   
   public double multiplication (double inp1, double inp2){
      return calcService.multiplication (inp1, inp2);
   }
   
   public double division(double inp1, double inp2){
      return calcService.division(inp1, inp2);
   }
}

Step 3 − Testing the MathApp class.

Let's test the MathApp class by injecting in it a mock of CalculatorMain. Mockito will create a mock.

File: MathAppTester.java

import static org.mockito.Mockito.doThrow;
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 will attach a runner to the test class that will // initialize the test data
@RunWith(MockitoRunner.class)
public class MathAppTester {

   // @TestSubject in mockito is an annotation used to identify // a class 
     // that is going to use the mock object
   @TestSubject
   MathApp MathApp = new MathApp();

   //@Mock in Mockito is an annotation used to create a mock object that is to be injected
   @Mock
   CalculatorMain calcService;

   @Test(expected = RuntimeException.class)
   public void testAdd(){
      //This adds the behavior to throw exception
      doThrow(new RuntimeException("Add operation not implemented"))
         .when(calcService).add(10.0,20.0);

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

Step 4 − Executing test cases.

Next, we create a java class file called TestRunner in C:\> Mockito_WORKSPACE to execute Test cases.

File: 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(MathAppTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
   
      System.out.println(result.wasSuccessful());
   }
} 

Step 5 − Verifying the Result

Finally, we compile the classes using the javac compiler.

C:\Mockito_WORKSPACE>javac CalculatorMain.java CalculatorMain.java MathAppTester.java TestRunner.java

Now run the Test Runner to see the result −

C:\Mockito_WORKSPACE>java TestRunner

Verify the output.

testAdd(MathAppTester): Add operation not implemented
false

FAQs

  1. What is doAnswer Mockito?
    The doAnswer() is used when we want to stub a method (void method) with a generic answer. Answer signifies an action that is to be executed, and a return value is returned once you interact with the mock.
  2. What is an exception?
    Exceptions are events that occur during the execution process of a program. This process disrupts the typical workflow of the program's instructions.
  3. What is the difference between Mockito and JUnit?
    JUnit is a framework that aids with writing and performing unit tests. Mockito, on the other hand, is a framework that is explicitly used to efficiently write certain kinds of tests.
  4. Should I use Mockito?
    The purpose of Mockito is to simplify the development of a test by mocking external dependencies and using them in a test code. As a result, Mockito provides a simpler test code that is more comfortable to read, understand, and modify.
  5. What is @Spy Annotation in Mockito?
    @Spy enables the creation of a partially mock object. Alternatively, @Spy allows the shorthand wrapping of the field instances in a spy object. 

Key Takeaways

In this article, we have extensively discussed Exception Handling in Mockito with the help of an examples. 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 Testing Exceptions 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