Mockito timeout Verification Mode

The timeout method in the Mockito framework is used to verify that a method on a mock object is called within a given period. This allows you to test asynchronous code by repeatedly triggering the verification until the specified timeout is reached.

Table of Contents

  1. Introduction
  2. timeout Method Syntax
  3. Examples
    • Basic Usage
    • Verifying Asynchronous Code
  4. Real-World Use Case
  5. Conclusion

Introduction

Mockito is a popular library in Java for creating and managing mock objects. The timeout method, which belongs to the Mockito class, allows you to verify that a method is called within a given time period. This can be useful for testing asynchronous code where you need to ensure that a method is invoked within a certain timeframe.

timeout Method Syntax

Verifying Method Calls with Timeout

import static org.mockito.Mockito.timeout;

static VerificationWithTimeout timeout(long millis)

Specifies that verification should be triggered over and over until the given amount of milliseconds.

Parameters:

  • millis: The maximum time to wait for the verification to succeed, in milliseconds.

Returns:

  • A VerificationWithTimeout object that can be used to verify the method calls within the specified timeout.

Examples

Basic Usage

Verify that a method is called within a specified timeout.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.timeout;
import org.junit.jupiter.api.Test;

public class BasicTimeoutTest {
    @Test
    void testTimeout() {
        UserService mockUserService = mock(UserService.class);

        // Perform some interaction in a separate thread
        new Thread(() -> {
            try {
                Thread.sleep(500); // Simulate async behavior
                mockUserService.deleteUser("123");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Verify that deleteUser was called within 1 second
        verify(mockUserService, timeout(1000)).deleteUser("123");
    }
}

class UserService {
    public void deleteUser(String userId) {
        // Method implementation
    }
}

Verifying Asynchronous Code

Verify that a method is called within a specified timeout in an asynchronous context.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.timeout;
import org.junit.jupiter.api.Test;

public class AsyncTimeoutTest {
    @Test
    void testAsyncTimeout() {
        UserService mockUserService = mock(UserService.class);

        // Perform some interaction in a separate thread
        new Thread(() -> {
            try {
                Thread.sleep(300); // Simulate async behavior
                mockUserService.updateUser("123");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Verify that updateUser was called within 1 second
        verify(mockUserService, timeout(1000)).updateUser("123");
    }
}

class UserService {
    public void updateUser(String userId) {
        // Method implementation
    }
}

Real-World Use Case

Testing Asynchronous Service Calls

In a real-world scenario, you might have asynchronous service calls that you need to test. The timeout method can help ensure that these calls are made within a specified time frame, providing confidence in the reliability and performance of your asynchronous code.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.timeout;
import org.junit.jupiter.api.Test;

interface PaymentService {
    void processPayment(String orderId);
}

class OrderService {
    private final PaymentService paymentService;

    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void placeOrder(String orderId) {
        new Thread(() -> {
            try {
                Thread.sleep(200); // Simulate async payment processing
                paymentService.processPayment(orderId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

public class OrderServiceTest {
    @Test
    void testAsyncPaymentProcessing() {
        PaymentService mockPaymentService = mock(PaymentService.class);
        OrderService orderService = new OrderService(mockPaymentService);

        // Place an order, which triggers async payment processing
        orderService.placeOrder("123");

        // Verify that processPayment was called within 500 milliseconds
        verify(mockPaymentService, timeout(500)).processPayment("123");
    }
}

In this example, the OrderServiceTest class uses Mockito’s timeout method to verify that the processPayment method is called within 500 milliseconds. This helps ensure that the OrderService correctly handles asynchronous payment processing.

Conclusion

The timeout verification mode in Mockito is used for testing asynchronous code. By using timeout, you can ensure that methods on mock objects are called within a specified time frame, improving the accuracy and reliability of your tests. This helps ensure that your asynchronous code behaves as expected and meets performance requirements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top