如何通过参数返回Mockito中的方法



我想通过方法的参数我模拟返回值

示例:

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

有没有办法实现这一目标?

您必须利用thenAnswer功能:

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);

例如:

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

相关内容

  • 没有找到相关文章

最新更新