Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.(启用存根方法。 当你希望模拟在调用特定方法时返回特定值时使用它。)
Simply put: "When the x method is called then return y".
when() is a successor of deprecated Mockito.stub(Object)
Examples:
when(mock.someMethod()).thenReturn(10);
//you can use flexible argument matchers, e.g:
when(mock.someMethod(anyString())).thenReturn(10);
//setting exception to be thrown:
when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
//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