如何在 thenReturn 函数中返回传递给 Mockito-mocked 方法的参数



这就是我想要实现的目标。

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调用。

那么如何在测试期间返回传入的第一个参数呢?

你通常用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);
    }
 };

您可以将其简化为

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

你也可以使用org.mockito.AdditionalAnswers

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

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

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

相关内容

  • 没有找到相关文章

最新更新