Mockito 问题-Stubber 中的when(java.lang.Void) 不能应用于void

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25249902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:59:23  来源:igfitidea点击:

Mockito issue - when(java.lang.Void) in Stubber cannot be applied to void

javamockingmockito

提问by mstrom

I can't figure out why the doNothingisn't working for this? Any ideas?

我不明白为什么这doNothing不起作用?有任何想法吗?

@Captor
ArgumentCaptor<GenericClass<someOtherClass>> captor;
...
Mockito.doNothing().when(mockObject.methodToStub(captor.capture()));

The error is:

错误是:

Exception: when(java.lang.Void) in Stubber cannot be applied to void

Exception: when(java.lang.Void) in Stubber cannot be applied to void

回答by Paulo Schreiner

Although you ask why doNothing doesn't work, I get that you actually want to capture the argument for methodToStub.

尽管您问为什么 doNothing 不起作用,但我知道您实际上想要捕获 methodToStub 的参数。

The most straightforward way to do this would be:

最直接的方法是:

verify(mockObject).methodToStub(captor.capture());

If you just want you mock to do nothing at all on a void method call, remeber that doing nothing is the defaultfor void methods on mocks.

如果您只想模拟在 void 方法调用上什么都不做,请记住,什么都不做是模拟上的 void 方法的默认设置

If for some reason you still need to call doNothing, you should take care with the parentheses position. It should look like this:

如果由于某种原因你仍然需要调用doNothing,你应该注意括号的位置。它应该是这样的:

doNothing().when(mockObject).methodToStub(any());

or doNothing().when(mockObject).methodToStub(captor.capture());

或 doNothing().when(mockObject).methodToStub(captor.capture());

回答by Brice

This stub is wrong :

这个存根是错误的:

doNothing().when(mockObject.methodToStub(captor.capture())); // wrong

methodToStub(...)must be outside the whenif using this API style (it should only contain the mock) :

methodToStub(...)必须在whenif 使用此 API 样式之外(它应该只包含模拟):

doNothing().when(mockObject).methodToStub(captor.capture()); // correct

Tho remarks however :

然而,Tho 评论道:

  1. doNothingis the default for void methods for a mock.
  2. You can use the BDDMockitoaliases that enables your code to be real à laBehavior Driven Development
  1. doNothing是模拟的 void 方法的默认值。
  2. 您可以使用BDDMockito,使您的代码的别名是真正的驱动开发行为