gpt4 book ai didi

java - Mockito 在 Spy 上使用 doAnswer

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:55 25 4
gpt4 key购买 nike

我想使用 when(spy).thenAnswer(new Answer())但似乎 thenAnswer 只适用于模拟而不适用于 spy 。我想使用 spy ,因为我只想 stub 特定方法。

有没有办法对 spy 对象进行回答?

最佳答案

如官方 documentation 所述,这是可能的,有时甚至建议:

Important gotcha on spying real objects!

Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing.

但是,再次作为 doc状态:

Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

你的方法无效吗?

文档中的示例如果无效:

doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Mock mock = invocation.getMock();
return null;
}
}).when(mock).someMethod();

因此,如果您的方法无效,您应该使用以下代码:

MyObject spy = spy(myObject);

doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null;
}
}).when(spy).notify();

或者如果它不是空的:

when(spy.toString()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return "this";
}
});

关于java - Mockito 在 Spy 上使用 doAnswer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764065/

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