Mockito.when()

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");

 //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");

 //shorter version for consecutive method calls throwing exceptions:
 when(mock.someMethod("some arg"))
  .thenThrow(new RuntimeException(), new NullPointerException();

 
For stubbing void methods with throwables see: Mockito.doThrow(Throwable)

Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing.(可以覆盖残留物:例如,普通残留物可以进入夹具设置,但是测试方法可以覆盖它。 请注意,覆盖残片是一种潜在的代码异味,指出了太多的残片。)

Once stubbed, the method will always return stubbed value regardless of how many times it is called.(一旦存留,该方法将始终返回存根值,而不管其被调用多少次。)

Last stubbing is more important - when you stubbed the same method with the same arguments many times.(最后的根部更重要 - 当你多次使用相同的参数对相同的方法进行存根时。)

Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.(虽然可以验证存根调用,但通常它只是多余的。 假设你已经存根foo.bar()。 如果你的代码关心foo.bar()返回的内容,那么其他的内容就会中断(通常在verify()被执行之前)。 如果你的代码不关心得到(0)返回的内容,那么它不应该被截断。 不服气? 看这里。)

See examples in javadoc for Mockito class

Type Parameters:
Parameters:
methodCall method to be stubbed
Returns:
OngoingStubbing object used to stub fluently. Do not create a reference to this returned object.

你可能感兴趣的:(Test)