Home > Java > javaTutorial > body text

How Can I Test Nondeterministic Responses with Mockito?

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

 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:

<code class="java">ExecutorCompletionService<T> completionService = new ExecutorCompletionService<>(service);

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

for (int i = 0; i < calls.size(); i ++) {
    try {
        T t = completionService.take().get();
        // do some stuff that I want to test
    } catch (...) { }        
}</code>
Copy after login

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:

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

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.

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