Mockito.when()

Mockito.when() 方法用于在模拟对象上调用时指定特定的返回值。这允许你在测试中控制模拟对象的行为。一旦存根,方法将始终返回存根值,无论被调用多少次。然而,过度的存根可能是代码质量问题的信号。尽管可以验证存根调用,但在大多数情况下这是冗余的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:
<T>
Parameters:
methodCall method to be stubbed
Returns:
OngoingStubbing object used to stub fluently. Do not create a reference to this returned object.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值