如何在thenReturn函数中返回传递给Mockito模拟方法的参数?

时间:2019-06-13 05:27:39

标签: java mockito java-10

这是我要实现的目标。

MyClass doSomething =  mock(MyClass.class);
when(doSomething.perform(firstParameter, any(Integer.class), any(File.class)))
    .thenReturn(firstParameter);

基本上,我希望模拟类的方法始终返回传递给该方法的第一个参数。

我曾经尝试使用ArgumentCaptor

ArgumentCaptor<File> inFileCaptor = ArgumentCaptor.forClass(File.class);
MyClass doSomething = mock(MyClass.class);
when(doSomething.perform(inFileCaptor.capture(), any(Integer.class), any(File.class)))
    .thenReturn(firstParameter);

但是mockito却因以下错误消息而失败:

No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()

Examples of correct argument capturing:
    ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
    verify(mock).doSomething(argument.capture());
    assertEquals("John", argument.getValue().getName());

我认为ArgumentCaptor类仅适用于verify调用。

那么如何在测试过程中将第一个参数作为传入参数返回?

2 个答案:

答案 0 :(得分:2)

通常使用thenAnswer进行此操作:

when(doSomething.perform(firstParameter, any(Integer.class), 
             any(File.class)))
    .thenAnswer(new Answer<File>() {
          public File answer(InvocationOnMock invocation) throws Throwable {
        return invocation.getArgument(0);
    }
 };

答案 1 :(得分:2)

您也可以使用org.mockito.AdditionalAnswers

when(doSomething.perform(eq(firstParameter), any(Integer.class), any(File.class)))
    .thenAnswer(AdditionalAnswers.returnsFirstArg())

@Fred解决方案也可以用lambda编写

when(doSomething.perform(eq(firstParameter), any(Integer.class), any(File.class)))
        .thenAnswer(i->i.getArgument(0));