Home > Java > javaTutorial > body text

How can I simulate different return values for repeated method calls with Mockito?

Patricia Arquette
Release: 2024-10-27 22:45:30
Original
310 people have browsed it

How can I simulate different return values for repeated method calls with Mockito?

Customizing Mockito Return Values for Repeated Method Calls

When testing scenarios involving non-deterministic responses, it can be useful to simulate a method returning different values upon subsequent invocations. Mockito, a popular Java mocking framework, provides an elegant solution for this conundrum.

Consider the example code provided, where an ExecutorCompletionService is used to group tasks and collect their results. To effectively test the logic regardless of the task execution order, we need to ensure that the method completionService.take() returns different values at different times.

Mockito provides the thenReturn method to control the return values of stubbed methods. Notably, you can specify multiple values within the parentheses of thenReturn. Upon each invocation of the method, Mockito will return the values in the specified order. For example:

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

In this example, the first call to completionService.take() will return value1, the second call will return value2, and the third call will return value3. Once all the specified values have been returned, Mockito will continue returning the last value for subsequent calls.

By utilizing this technique, you can effectively simulate non-deterministic responses and ensure that your test logic remains robust regardless of the order in which tasks complete their execution.

The above is the detailed content of How can I simulate different return values for repeated method calls with Mockito?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template