mockito:有没有办法捕获存根方法的返回值?
如果我模拟一个方法来返回某个对象的新实例,如何捕获返回的实例?
例如:
when(mock.someMethod(anyString())).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return new Foo(args[0])
}
});
显然,我可以有一个 Foo 类型的字段,并在 answer
内部将其设置为新实例,但是有更好的方法吗?像 ArgumentCaptor 这样的东西?
If I mock a method to return a new instance of some object, how can I capture the returned instance?
E.g.:
when(mock.someMethod(anyString())).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return new Foo(args[0])
}
});
Obviously, I can have a field of type Foo and inside answer
set it to the new instance, but is there a nicer way? Something like ArgumentCaptor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想做类似的事情,但使用的是监视对象而不是模拟对象。具体来说,给定一个间谍对象,我想捕获返回值。根据 Andreas_D 的回答,这就是我的想法。
预期用途:
I wanted to do something similar, but with a spied object rather than a mock. Specifically, given a spied object, I want to capture the return value. Based on Andreas_D's answer, here's what I came up with.
Intended usage:
看起来您想要观察然后
Answer
实例,并在每次调用answer
方法时接收通知(这会触发创建新的Foo
)。那么为什么不发明一个 ObservableAnswer 类:预期用途:
Looks like you want to observe and then
Answer
instances, and receive notifications each time theanswer
method is called (which triggers the creation of a newFoo
). So why not invent anObservableAnswer
class:Intended use:
作为 @JeffFairley 答案的替代方案,您可以利用
AtomicReference
。它将充当Holder
,但我更喜欢它而不是真正的持有者,因为它是在 Java 的基本框架中定义的。在我看来: ResultCaptor 是很酷的东西,将来可能会集成到 Mockito 中,可广泛重用且语法简短。但如果您偶尔需要,那么 lambda 的几行可以更简洁
As an alternative to @JeffFairley's answer, you can leverage
AtomicReference<T>
. It will act as aHolder<T>
, but I prefer this over real holders because it's defined in Java's base framework.In my opinion: ResultCaptor is cool stuff that may be integrated in Mockito in the future, is widely reusable and short in syntax. But if you need that sporadically, then few lines of a lambda can be more concise
调用 doAnswer,然后调用真正的方法并将返回值添加到列表中,如下所示:
完整示例:
Call doAnswer, then call the real method and add the returning value to a list, as the following:
A full example: