Home  >  Article  >  Java  >  How to Mock Return Values Based on Input Arguments with Mockito?

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

DDD
DDDOriginal
2024-10-24 03:46:02583browse

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>

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>

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!

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