1

I would like to pass argument of method I mock to return value

Example:

when(mockedObject.printEntries(anyLong()).thenReturn("%d entries");

Is there a way to achieve that?

Maciej Kowalski
  • 23,799
  • 10
  • 49
  • 59
pixel
  • 23,075
  • 32
  • 129
  • 220

2 Answers2

5

You have to take advantage of the the thenAnswer feature:

Answer<String> answer = new Answer<String>() {
    public String answer(InvocationOnMock invocation) throws Throwable {
        Long long = invocation.getArgumentAt(0, Long.class);
        return long + " entries";
    }
};


when(mockedObject.printEntries(anyLong()).thenAnswer(answer);
Maciej Kowalski
  • 23,799
  • 10
  • 49
  • 59
1

For example:

    when(mockedObject.printEntries(anyLong()).thenAnswer(invocationOnMock -> {
        Long aLong = invocationOnMock.getArgumentAt(1, Long.class);
        return aLong + 2;
    });
Merch0
  • 474
  • 5
  • 13