为什么 Mock 对象有 doreturn 和 thenreturn for mock?

why Mock object has doreturn and thenreturn for mock?

注意:我知道在间谍中我们可以区分这两者。 我遍历了互联网,但我仍然对 Mockito 中的 doreturn/when 和 when/thenreturn 有一些疑问。下面是我的疑问,

1)doreturn/when 和 when/thenreturn 对模拟对象的行为相同吗? 即:无论您是为模拟对象调用 doreturn/when 还是 when/thenreturn 都没有关系,它不会调用真正的方法,而是调用存根调用。 我对此的理解是否正确?

2)doreturn/when 和 when/thenreturn 仅对 Mockito 中的间谍对象有所不同。 即 doreturn/when - 不会调用真实方法,when/thenreturn 会调用真实方法 method.Is 我的理解正确吗?

如果我对以上两点的理解是正确的,那么我们应该始终使用 doreturn/when 这样我们就不需要学习 2 语法,对吗?

doReturn()Mockito documentation 状态:

You can use doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() in place of the corresponding call with when(), for any method. It is necessary when you

  • stub void methods
  • stub methods on spy objects (see below)
  • stub the same method more than once, to change the behaviour of a mock in the middle of a test.

还有...

Use doReturn() in those rare occasions when you cannot use when(Object).

举个例子...

when(mock.foo()).thenThrow(new RuntimeException());

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar");

//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();

一般来说,你应该使用when(...).thenReturn(...)语法,doReturn(...).when(...)语法很少见。但是,重要的是要注意模拟 void 方法需要 when(...) 模式,这种情况并不少见。只是 doReturn(...) 语法不太常用。

具体回答您的问题:

  1. 不,这两种语法的工作方式略有不同 - 'doReturn(...)' 能够设置模拟对象来记录行为 模拟之前方法被调用,而 'when(...)' 语法通过做一些幕后的 jiggery-pokery 来设置一个 'thenReturn(...)' 方法可以工作的存根处理程序。它们通常具有相同的效果,但在上面的极端情况下,实现差异变得明显。

  2. 对于模拟,when(...) 调用模拟对象上的存根方法。这就是为什么上面关于重新定义存根行为的极端情况很重要。

自己做了之后才知道:

  1. doreturn/when 和 when/thenreturn 对于模拟对象是相同的。 None 其中调用实际方法
  2. doreturn/when 和 when/thenreturn 对侦测对象有不同的行为。 doreturn/when - 它不会调用间谍对象的真正方法 when/thenreturn - 它将在侦测对象上调用真正的方法

希望对您有所帮助!