Home > Java > javaTutorial > body text

How to Mock Method Returns to Echo Input Arguments in Mockito?

Linda Hamilton
Release: 2024-10-24 03:07:01
Original
534 people have browsed it

How to Mock Method Returns to Echo Input Arguments in Mockito?

Mocking Method Return: Echoing Input Arguments

When testing software, it can be beneficial to have mocked methods return the arguments that are passed to them. This behavior can be particularly useful when verifying interactions or testing the flow of data through a system.

For Mockito versions 1.9.5 and above, this functionality can be achieved succinctly using lambda expressions:

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

In this case, the i parameter represents an InvocationOnMock instance, which provides access to the arguments passed to the mocked method.

For earlier versions of Mockito, a custom Answer is required:

<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

Using this approach, the mock will return the same String that was passed to myFunction().

The above is the detailed content of How to Mock Method Returns to Echo Input Arguments 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!