且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不运行方法的情况下模拟方法调用和返回值?

更新时间:2021-09-10 00:54:10

当你调用时

Mockito.when(spy.isCertainValue()).thenReturn(true);

方法 isCertainValue()被调用这里。这就是Java的工作原理:要评估 Mockito.when 的参数, spy.isCertainValue()的结果必须因此必须调用该方法。

the method isCertainValue() is getting called here. This is how Java works: to evaluate the argument of Mockito.when, the result of spy.isCertainValue() must be evaluated so the method must be called.

如果您不希望这种情况发生,可以使用以下构造

If you don't want that to happen, you can use the following construct:

Mockito.doReturn(true).when(spy).isCertainValue();

这将具有相同的模拟效果,但不会使用此方法调用该方法。

This will have the same mocking effect but the method won't be called with this.