Home > Java > javaTutorial > body text

How to Mock Return Values Based on Input Arguments with Mockito?

DDD
Release: 2024-10-24 03:46:02
Original
633 people have browsed it

How to Mock Return Values Based on Input Arguments with Mockito?

Mocking Return Values from Passed Arguments

When testing methods with specific input parameters, it can be necessary to have the mock method return the same value that was passed to it. Mockito provides several methods to achieve this, depending on the version being used.

For Mockito 1.9.5 and Java 8 :

Mockito added support for lambda expressions, allowing for direct return of the passed argument:

<code class="java">when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);</code>
Copy after login

For Older Mockito Versions:

Before Mockito 1.9.5, you can use Answer in the thenAnswer method:

<code class="java">when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    }
});</code>
Copy after login

The above is the detailed content of How to Mock Return Values Based on Input Arguments with Mockito?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
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!