java Mockito / PowerMocktio doNothing for none void 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25018330/
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
Mockito / PowerMocktio doNothing for none void method
提问by Mat
I need a method which returns something to do nothing when invoked during testing, the class instance which owns the method is implemented as a spy.
我需要一个方法,它在测试期间调用时返回什么都不做,拥有该方法的类实例被实现为间谍。
I am aware the doNothing() method only works with void methods. Is there a way to get the same behaviour with a method that returns something?
我知道 doNothing() 方法仅适用于 void 方法。有没有办法通过返回某些内容的方法获得相同的行为?
Thank you!
谢谢!
采纳答案by John B
Use when(spy.myMethod()).thenReturn(null)
. This will prevent the spy from invoking the wrapped instance. You have to tell Mockito what to return for a method that returns something. The default behavior for a mock
is to return null
. The default behavior for a spy
is to call the wrapped object. When you stub
a method in a spy
it prevents the call to the wrapped object and executes the specified behavior.
使用when(spy.myMethod()).thenReturn(null)
. 这将防止间谍调用包装的实例。你必须告诉 Mockito 为返回某些东西的方法返回什么。a 的默认行为mock
是 return null
。a 的默认行为spy
是调用包装的对象。当您stub
在 a 中使用方法时,spy
它会阻止对包装对象的调用并执行指定的行为。
Per documents of Spy, you could also do doReturn(null).when(spy).myMethod();
根据Spy 的文件,您也可以这样做doReturn(null).when(spy).myMethod();