我使用Mockito有一行代码:
when(mock.method()).thenReturn(foo).thenReturn(bar).thenThrow(new Exception("test"));
上述声明是否与相同
when(mock.method()).thenReturn(foo)thenThrow(new Exception("test"));
when(mock.method()).thenReturn(bar).thenThrow(new Exception("test"));
请有人解释一下,thenReturn
将如何执行?它是如何工作的?
快速查看Mockito的文档将提供答案。
//you can set different behavior for consecutive method calls.
//Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
//Alternative, shorter version for consecutive stubbing:
when(mock.someMethod("some arg"))
.thenReturn("one", "two");
//is the same as:
when(mock.someMethod("some arg"))
.thenReturn("one")
.thenReturn("two");
基本上,多次调用thenReturn将定义该方法在多次调用中的行为。