gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:45:03 32 4
gpt4 key购买 nike

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

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

关于java - 如何在 thenReturn 函数中返回传递给 Mockito 模拟方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573861/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com