Home > Java > javaTutorial > How to Return an Argument to a Mocked Method in Mockito?

How to Return an Argument to a Mocked Method in Mockito?

Mary-Kate Olsen
Release: 2024-10-23 22:13:02
Original
800 people have browsed it

How to Return an Argument to a Mocked Method in Mockito?

How to Make a Mocked Method Return an Argument Passed to It Using Mockito

Mockito is a Java mocking framework that allows the creation of mock objects for testing purposes. Mocking methods helps test code independently of its dependencies. In this scenario, we want to mock a method to return a value that was passed to it during the method call.

Solution:

Since Mockito version 1.9.5 and Java 8, lambda expressions can be utilized to achieve the desired functionality. Here's how:

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

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

Alternative Solution for Older Versions:

For older versions of Mockito, an Answer can be implemented to achieve the same result. Here's an example:

<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

In this Answer implementation, the arguments array is retrieved from the InvocationOnMock instance, and the first argument (string) is returned.

Using these methods, you can configure mocked methods in Mockito to return values based on the arguments passed to them, allowing for more flexible and realistic testing scenarios.

The above is the detailed content of How to Return an Argument to a Mocked Method in Mockito?. 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