"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Mock Methods to Return Arguments Received in Java?

How to Mock Methods to Return Arguments Received in Java?

Published on 2024-11-16
Browse:121

How to Mock Methods to Return Arguments Received in Java?

Mocking Methods to Return Arguments Received

In object-oriented programming, mocking frameworks like Mockito are used to create a mock object that simulates the behavior of a real object for testing purposes. One common scenario in testing is the need to have a mocked method return the same argument that was passed to it.

Mockito and Lambda Expressions (Mockito 1.9.5 and Java 8 )

For versions of Mockito 1.9.5 and later in conjunction with Java 8 or above, you can leverage lambda expressions to achieve this behavior:

when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);

Here, i represents an instance of InvocationOnMock, and getArguments()[0] retrieves the first argument passed to the mocked method.

Mockito and Custom Answers (Older Versions)

For older versions of Mockito, you can use a custom Mockito Answer implementation:

MyInterface mock = mock(MyInterface.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    }
});

This custom Answer retrieves the passed argument and returns it, allowing the mocked method to echo the received input.

Release Statement This article is reprinted at: 1729677594 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3