Home > Java > javaTutorial > How to Mock Methods to Return Arguments Received in Java?

How to Mock Methods to Return Arguments Received in Java?

Mary-Kate Olsen
Release: 2024-10-23 22:18:29
Original
1030 people have browsed it

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]);
Copy after login

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:

<code class="java">MyInterface mock = mock(MyInterface.class);
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 custom Answer retrieves the passed argument and returns it, allowing the mocked method to echo the received input.

The above is the detailed content of How to Mock Methods to Return Arguments Received 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