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
  • 25,605
  • 12
  • 54
  • 63
pixel
  • 24,905
  • 36
  • 149
  • 251

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
  • 25,605
  • 12
  • 54
  • 63
1

For example:

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