Ant*_*ong 5 java mockito java-10
这就是我想要实现的目标。
MyClass doSomething = mock(MyClass.class);
when(doSomething.perform(firstParameter, any(Integer.class), any(File.class)))
.thenReturn(firstParameter);
Run Code Online (Sandbox Code Playgroud)
基本上我希望模拟类的方法始终返回传递到该方法中的第一个参数。
我尝试过使用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);
Run Code Online (Sandbox Code Playgroud)
但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());
Run Code Online (Sandbox Code Playgroud)
我认为该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);
}
};
Run Code Online (Sandbox Code Playgroud)
你可以将其简化为
when(doSomething.perform(firstParameter, any(Integer.class), any(File.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
Run Code Online (Sandbox Code Playgroud)
你也可以这样做org.mockito.AdditionalAnswers
when(doSomething.perform(eq(firstParameter), any(Integer.class), any(File.class)))
.thenAnswer(AdditionalAnswers.returnsFirstArg())
Run Code Online (Sandbox Code Playgroud)
@Fred 解决方案也可以用 lambda 编写
when(doSomething.perform(eq(firstParameter), any(Integer.class), any(File.class)))
.thenAnswer(i->i.getArgument(0));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5187 次 |
| 最近记录: |