Mockito/PowerMocktio doNothing for none无效方法 [英] Mockito / PowerMocktio doNothing for none void method
问题描述
我需要一个在测试期间被调用时不返回任何内容的方法,拥有该方法的类实例被实现为间谍.
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.
我知道doNothing()方法仅适用于void方法.有没有一种方法可以返回返回值的方法来获得相同的行为?
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?
谢谢!
推荐答案
使用when(spy.myMethod()).thenReturn(null)
.这将防止间谍调用被包装的实例.您必须告诉Mockito对于返回某些内容的方法要返回什么. mock
的默认行为是返回null
. spy
的默认行为是调用包装的对象.在spy
中的stub
方法中,它将阻止对包装对象的调用,并执行指定的行为.
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.
对于间谍的文档,您也可以做doReturn(null).when(spy).myMethod();
Per documents of Spy, you could also do doReturn(null).when(spy).myMethod();
这篇关于Mockito/PowerMocktio doNothing for none无效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!