Home  >  Article  >  Java  >  How to Pass Arguments Back from Mocked Methods in Java?

How to Pass Arguments Back from Mocked Methods in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 05:05:30646browse

How to Pass Arguments Back from Mocked Methods in Java?

Returning Passed Arguments from Mocked Methods

In certain scenarios, it may be desirable for a mocked method to return the same argument that was passed to it. Mockito, a well-known mocking framework for Java, provides various approaches to achieve this behavior:

Mockito 1.9.5 with Java 8

Utilizing lambda expressions, you can now succinctly define the behavior:

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

Older Mockito Versions

Alternatively, for older versions of Mockito, you can create a custom Answer:

<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>

This Answer implementation retrieves the first argument from the invocation and returns it, effectively passing back the same string that was passed to the mocked method.

The above is the detailed content of How to Pass Arguments Back from Mocked Methods in Java?. 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