Table of contents
1.
Introduction
2.
Getting started
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Mockito Timeouts

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

Introduction

In software development, one gets to test its application whether it is expected to do so or not. For that reason, Mockito provides a Timeout option that may be used to see if a method is called within a certain amount of time.


So let's get started with writing our timeout in mockito.

Getting started

Assuming that you are familiar with the project setup in maven. Let see the practical example

1. Create a CalculatorService interface to offer mathematical functions.

public interface CalculatorService {
   public double add(double value1, double value2);

   public double subtract(double value1, double value2);

   public double multiply(double value1, double value2);

   public double divide(double value1, double value2);
}

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

2. Create a java class, MathApplication.

public class MathApplication {
   private CalculatorService calcService;

   public void setCalculatorService(CalculatorService calcService) {
       this.calcService = calcService;
   }

   public double add(double value1, double value2) {
       return calcService.add(value1, value2);
   }

   public double subtract(double value1, double value2) {
       return calcService.subtract(value1, value2);
   }

   public double multiply(double value1, double value2) {
       return calcService.multiply(value1, value2);
   }

   public double divide(double value1, double value2) {
       return calcService.divide(value1, value2);
   }
}
You can also try this code with Online Java Compiler
Run Code


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



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

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

// To initialise the test data, @RunWith connects a runner to the test class.
@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 behaviour to add numbers
       when(calcService.add(20.0, 50.0)).thenReturn(70.0);

       // subtract the behaviour to subtract numbers
       when(calcService.subtract(50.0, 10.0)).thenReturn(40.0);

       // test the subtract functionality
       Assert.assertEquals(mathApplication.subtract(50.0, 20.0), 30.0, 0);

       // test the add functionality
       Assert.assertEquals(mathApplication.add(50.0, 10.0), 60.0, 0);

       // ensure that the call to add method is performed in less than 500 milliseconds.
       verify(calcService, timeout(500)).add(20.0, 10.0);

       // to ensure that multiplication invocations can be examined within a particular time window, an invocation count can be supplied.
       verify(calcService, timeout(100).times(1)).subtract(20.0, 10.0);
   }
}
You can also try this code with Online Java Compiler
Run Code

4. Create a file name MathApplicationTester.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());
  }
}
You can also try this code with Online Java Compiler
Run Code


5. In the terminal, execute this command.

javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java

6. Execute the java file.

java TestRunner

FAQs

1. What is the spy method in Mockito?

Ans: A Spy is similar to a partial mock in that it tracks the interactions with the object. It also allows us to use all of the object's standard methods. When we call a spy object method, the real method is called as well (unless it is stubbed).


2. What does Mockito verify?
Ans: The Mockito Verify methods are used to verify that a particular activity occurred. To ensure that specified methods are called, we may utilise Mockito verify methods at the conclusion of the testing method code.


3. What are test doubles in unit testing?
Ans: Any number of substitute items that make testing simpler are referred to as test doubles. Test duplicates are used for software integrations or features that are difficult to test. When a system or process, while not error-prone in and of itself, adds a significant amount of time and effort to a test, this is an excellent use case for test doubles.


4. Can the interface be mocked?
Ans: To construct a fake object of a particular class or interface, use the mock() function of the Mockito class. This is the most basic method of mocking an object. We may also use the @Simulate annotation to mock an object. This can be done in the setup function of the testing framework or in the test procedure that runs before the tests.

Key Takeaways

If you've made it this far, it's because you're interested in learning more. The article covered the important topic related to the timeout in mockito testing library in java and reading implementation of the test cases through practical examples.

You might be interested in articles such as Mock Annotaion and Creating mock and need for mocking. Hence never stop your quest for learning. Do give an upvote to the article if you enjoyed it. We wish you Good Luck! Keep coding and keep reading Ninja.

Happy Learning

Live masterclass