java 使用 Mockito 时,mock() 和 stub() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5261194/
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-10-30 10:17:49  来源:igfitidea点击:

What is the difference between mock() and stub() when using Mockito?

javamockito

提问by Tom

They both seem to do the same thing - why would you use one in preference to the other?

他们似乎都在做同样的事情——为什么你会优先使用另一个?

org.mockito.Mockito.stub()
org.mockito.Mockito.mock()

采纳答案by Andy Thomas

You can use a mock object to verify that you have called it in the way expected. In Mockito, mocked objects are automatically stubs, and verification occurs explicitly.

您可以使用模拟对象来验证您是否以预期的方式调用了它。在 Mockito 中,被模拟的对象是自动存根的,并且显式地进行验证。

From Mockito's "Why do we need another mocking framework?":

来自 Mockito 的“为什么我们需要另一个模拟框架?”

 Separation of stubbing and verification. Should let me code in line with intuition: 
 stub before execution, selectively verify interactions afterwards. I don't 
 want any verification-related code before execution.

You can stub the behavior of calls before they're called. For example (from the Mockito home page):

您可以在调用之前对调用的行为进行存根。例如(来自 Mockito 主页):

 when( mockedList.get(0)).thenReturn( "first" );

You can verify interactions with mocked objects after they're called. For example:

您可以在调用后验证与模拟对象的交互。例如:

 verify( mockedList ).add("one");