"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 Can I Test Nondeterministic Responses with Mockito?

How Can I Test Nondeterministic Responses with Mockito?

Published on 2024-11-10
Browse:765

 How Can I Test Nondeterministic Responses with Mockito?

Testing Nondeterministic Responses with Mockito

When testing code that interacts with nondeterministic services, it can be difficult to ensure that the outcomes remain constant irrespective of the return order of methods. For instance, consider testing the following code, which uses an ExecutorCompletionService to group and process tasks:

ExecutorCompletionService completionService = new ExecutorCompletionService(service);

for (Callable t : ts)
    completionService.submit(request);

for (int i = 0; i 

To address this challenge, Mockito provides a means to configure subsequent invocations of a method to return different objects. By using the thenReturn method, you can specify the objects to be returned in order:

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

Each value will be returned sequentially, with the last value being used repeatedly once all other values have been exhausted. This allows you to test different scenarios and ensure that the outcome remains consistent regardless of the return order.

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