Mockito中调用thenCallRealMethod()前如何执行日志等额外操作?
Mockito 对应功能实现方案
Mockito 没有内置你设想的pipe()同名方法,但你可以通过官方提供的thenAnswer()接口实现完全一致的效果,这也是该场景下的标准实现方式:
有返回值方法写法
对应你示例中的calculateGrade()有返回值的场景,代码如下:
Mockito.when(student.calculateGrade()) .thenAnswer(invocation -> { // 提前执行的额外操作 System.out.println("blabla"); doSomethingElse("..."); // 调用真实方法,等价于后续链式调用thenCallRealMethod() return invocation.callRealMethod(); });
无返回值(void)方法写法
如果要Stub的是无返回值的方法,调整为doAnswer写法即可:
Mockito.doAnswer(invocation -> { System.out.println("blabla"); doSomethingElse("..."); invocation.callRealMethod(); // void方法固定返回null即可 return null; }).when(student).someVoidMethod();
内容的提问来源于stack exchange,提问作者ntson9p
相关产品推荐
相关产品推荐

