Mockito / PowerMocktio doNothing for none void method

别说谁变了你拦得住时间么 提交于 2019-12-05 11:47:47

问题


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?

Thank you!


回答1:


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.

Per documents of Spy, you could also do doReturn(null).when(spy).myMethod();



来源:https://stackoverflow.com/questions/25018330/mockito-powermocktio-donothing-for-none-void-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!