"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Mock Nondeterministic Method Behaviors in Mockito?

How to Mock Nondeterministic Method Behaviors in Mockito?

Published on 2024-11-14
Browse:365

How to Mock Nondeterministic Method Behaviors in Mockito?

Testing Nondeterminate Responses in Mockito

When testing asynchronous code that involves nondeterminate responses, such as those obtained from an ExecutorCompletionService, it becomes necessary to mock nondeterministic method behaviors. In this scenario, a method may return different objects upon subsequent invocations with the same arguments.

To achieve this in Mockito, use the thenReturn method with multiple arguments. The syntax is:

when(method-call).thenReturn(value1, value2, value3);

You can specify as many arguments as needed, all of the same type. The first value will be returned on the first method call, the second on the second, and so on. Once all the values have been returned, the last value will continue to be returned for subsequent calls.

For instance, the following code demonstrates how to test a method that calls an ExecutorCompletionService to retrieve tasks:

// Arrange
ExecutorCompletionService completionService = mock(ExecutorCompletionService.class);
when(completionService.take()).thenReturn(task1, task2, task3);

// Act
for (int i = 0; i 

In this example, the take method will initially return task1, then task2, and finally task3 for the first three calls. Afterward, the same value (task3) will be returned for all subsequent calls. This allows for the testing of nondeterministic responses while verifying that the outcome remains constant.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3