Home > Java > javaTutorial > body text

How to Mock Nondeterministic Method Behaviors in Mockito?

Mary-Kate Olsen
Release: 2024-10-28 04:30:02
Original
996 people have browsed it

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);
Copy after login

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<T> completionService = mock(ExecutorCompletionService.class);
when(completionService.take()).thenReturn(task1, task2, task3);

// Act
for (int i = 0; i < 3; i++) {
    T task = completionService.take().get();

    // Assert
    assertEquals(expectedTasks[i], task);
}
Copy after login

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.

The above is the detailed content of How to Mock Nondeterministic Method Behaviors in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!