Mockito.timeout() Example

1. Introduction

When testing asynchronous operations, it's crucial to be able to verify if a method was called within a specific time range. Mockito provides the timeout() method, enabling us to validate if a method on a mock was called within a certain duration. This is particularly helpful for ensuring the timeliness of certain operations, especially in concurrent applications.

2. Example Steps

1. Create a simple service that performs an asynchronous operation.

2. Mock this service and invoke the asynchronous method in a test class.

3. Use the verify() method combined with timeout() to check if the method was called within the desired time frame.

3. Mockito.timeout() Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

public class AsyncService {
    public void asyncMethod() {
        // Simulated async operation
    }
}

public class AsyncServiceTest {

    @Test
    public void testAsyncMethodWithTimeout() {
        // Mock the AsyncService
        AsyncService mockedAsyncService = mock(AsyncService.class);

        // Simulate an asynchronous operation using a separate thread
        new Thread(() -> {
            try {
                // Simulate some processing delay
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mockedAsyncService.asyncMethod();
        }).start();

        // Use verify() combined with timeout() to check if the method was called within 100 milliseconds
        verify(mockedAsyncService, timeout(100)).asyncMethod();

        System.out.println("Method verified within the specified timeout.");
    }
}

Output:

Method verified within the specified timeout.

4. Step By Step Explanation

1. We begin by creating a simple AsyncService with a method named asyncMethod, which represents an asynchronous operation.

2. In the AsyncServiceTest, we mock the AsyncService.

3. To simulate the asynchronous nature of the operation, we use a separate thread to delay the call to the asyncMethod of our mock by 50 milliseconds.

4. After invoking the asynchronous method, we utilize Mockito's verify() combined with timeout() to ensure that our mocked method was indeed called within the 100 milliseconds timeframe.

5. The output "Method verified within the specified timeout." confirms that the method was called within the stipulated time range.


Comments