Mockito链函数使用
Mockito chain function usage
当我模拟方法链时,我是否必须只用下面的格式编写它们
when(foo.getBar()).thenReturn(bar);
when(bar.getName()).thenReturn("Foo Bar");
或者我也可以使用以下格式吗?因为两者都为我工作,我问这个问题是因为有人告诉我我的第二种(以下)方法是错误的
when(foo.getBar()).thenReturn(bar);
when(foo.getBar().getName()).thenReturn("Foo Bar");
Mockito 常见问题解答addresses this explicitly:
Can I stub chained getters?
when(mock.getA().getB()).thenReturn(...);
This sort of stubbing, e.g. mock to return mock, to return mock, etc. should be used very sporadically, ideally never. It clearly points out violation of the Law of Demeter. You don't want to mess with Demeter. Since you have been warned check out Mockito deep stubs.
从技术角度来看,它是受支持的,部分原因是它与此没有区别:
when(foo.getBar()).thenReturn(bar);
foo.getBar();
when(bar.getName()).thenReturn("Foo Bar");
...这可能会干扰您需要 verify(foo, times(n)).getBar()
.
的 hopefully-unlikely 事件中的验证
当我模拟方法链时,我是否必须只用下面的格式编写它们
when(foo.getBar()).thenReturn(bar);
when(bar.getName()).thenReturn("Foo Bar");
或者我也可以使用以下格式吗?因为两者都为我工作,我问这个问题是因为有人告诉我我的第二种(以下)方法是错误的
when(foo.getBar()).thenReturn(bar);
when(foo.getBar().getName()).thenReturn("Foo Bar");
Mockito 常见问题解答addresses this explicitly:
Can I stub chained getters?
when(mock.getA().getB()).thenReturn(...);
This sort of stubbing, e.g. mock to return mock, to return mock, etc. should be used very sporadically, ideally never. It clearly points out violation of the Law of Demeter. You don't want to mess with Demeter. Since you have been warned check out Mockito deep stubs.
从技术角度来看,它是受支持的,部分原因是它与此没有区别:
when(foo.getBar()).thenReturn(bar);
foo.getBar();
when(bar.getName()).thenReturn("Foo Bar");
...这可能会干扰您需要 verify(foo, times(n)).getBar()
.