Mockito timeout()

1. Overview

In unit testing, it's not just about what gets executed but also when and how quickly it does. The Mockito.timeout() method helps you to validate the time behavior of your methods, ensuring they execute within a specified time duration. This becomes vital, especially when dealing with asynchronous operations. In this tutorial, we will explore the timeout() method, its application, and practical scenarios.

2. Development Steps

1. Set up a new Maven project.

2. Add the required Mockito and JUnit 5 dependencies.

3. Create a simple class named 'AsyncService' to demonstrate the usage of timeout().

4. Design a test class to demonstrate the Mockito.timeout() application.

5. Execute the test and review the results.

6. Understand the outcomes.

3. Dependencies (Mockito and JUnit 5)

<!-- JUnit 5 -->
<!-- Mockito -->

4. Code Program

// Step 3: Define the AsyncService class
class AsyncService {
    public void asyncMethod() throws InterruptedException {
        // Simulating some asynchronous operation
// Step 4: Develop the test class for AsyncService
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
public class AsyncServiceTest {
    public void testTimeout() throws InterruptedException {
        // Create a mock of AsyncService
        AsyncService mockService = mock(AsyncService.class);
        // Invoke the method
        // Verify that the method was called within 100 milliseconds
        verify(mockService, timeout(100)).asyncMethod();


The test will pass without any errors, indicating that the asyncMethod completed its execution within the specified 100 milliseconds timeout.

Code Explanation:

1. The AsyncService class contains a method named asyncMethod that simulates an asynchronous operation using Thread.sleep(50). This ensures the method takes 50 milliseconds to complete.

2. In the test, we create a mock of the AsyncService class.

3. We then invoke the asyncMethod.

4. Using Mockito's verify() in conjunction with timeout(), we ensure that our asyncMethod gets executed within 100 milliseconds.

5. As our asyncMethod only takes 50 milliseconds (due to our simulation), the verification passes.

5. Conclusion

The Mockito.timeout() method is a handy tool when it comes to ensuring time-bound execution in unit tests. It's crucial for testing asynchronous operations, where the responsiveness of a function is as important as its output. By leveraging this method, developers can safeguard against unforeseen delays and potential performance issues in their applications.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers