Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

Consider a method signature like:

public String myFunction(String abc);

Can Mockito help return the same string that the method received?

1 Answer

0 votes
by (46k points)

If you own Mockito 1.9.5 or higher, there is a static method that can execute the Answer object for you. You need to write something like this:

 Let's consider, we have an interface named Application with a method myFunction.

public interface Application {

  public String myFunction(String abc);

}

Here is the test method with a Mockito answer:

public void testMyFunction() throws Exception {

  Application mock = mock(Application.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];

    }

  });

  assertEquals("someString",mock.myFunction("someString"));

  assertEquals("anotherString",mock.myFunction("anotherString"));

}

In Mockito 1.9.5 and Java 8 there is a simpler way by using lambda functions:

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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...