Home > Java > javaTutorial > body text

How to Pass Arguments Back from Mocked Methods in Java?

Mary-Kate Olsen
Release: 2024-10-24 05:05:30
Original
650 people have browsed it

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

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

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!

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