Home  >  Article  >  Java  >  How to Test Nondeterminate Responses with Mockito and Multiple Method Invocations?

How to Test Nondeterminate Responses with Mockito and Multiple Method Invocations?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 00:31:30434browse

 How to Test Nondeterminate Responses with Mockito and Multiple Method Invocations?

Testing Nondeterminate Responses with Mockito and Multiple Method Invocations

In testing scenarios where a stubbed method returns different objects for multiple invocations with the same arguments, it becomes essential to ensure consistent outcomes regardless of the return order. To achieve this, Mockito provides an elegant solution.

For instance, consider the following test scenario where an ExecutorCompletionService is used to group and process tasks. The goal is to verify that the outcome remains constant irrespective of the order in which the tasks complete.

<code class="java">// ExecutorCompletionService completionService = new ExecutorCompletionService(service);
// for (Callable<T> t : ts) completionService.submit(request);</code>

To test the nondeterminate responses of the completion service, one can leverage Mockito's thenReturn method as follows:

<code class="java">when(completionService.take().get()).thenReturn(value1, value2, value3);</code>

The thenReturn method allows specifying multiple return values as arguments, ensuring that the stubbed method returns the desired objects in the specified order. The first value will be returned on the first invocation, followed by the second, and so on. Once all values are exhausted, the last value will be returned repeatedly.

This approach enables developers to test various scenarios where the order of method calls or the sequence of returned objects does not affect the expected outcome. It simplifies testing and ensures that the code is robust and reliable even in nondeterminate situations.

The above is the detailed content of How to Test Nondeterminate Responses with Mockito and Multiple Method Invocations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn