在mockito中执行doAnswer-何时进行惰性评估,何时进行评估? [英] doAnswer in mockito - when is it lazy evaluation and when is it eager?

查看:440
本文介绍了在mockito中执行doAnswer-何时进行惰性评估,何时进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有以下代码的模仿间谍:

I'm using mockito spy with this code:

Mockito.doAnswer(new Answer() {
    Object answer(InvocationOnMock invocation) {
         ImagesSorter mock = (ImagesSorter) invocation.getMock();
         Object[] args = invocation.getArguments();

         return mock.sortImages((List<Image>) args[0], (UserInfo) args[1],
                 fakeNowDate);
    }
}).when(imagesSorterSpy).sortImages(imagesAsInsertionOrder, user);

当结构为:

when(spy.method())./*...*/.

但是当结构为:

/*...*/.when(spy).method()

反之亦然吗?意思是/*...*/.when(spy).method()是渴望的,而when(spy.method())./*...*/.是懒惰的?喜欢do..while loop吗?

Shouldn't it be vise versa? Meaning /*...*/.when(spy).method() is eager versus when(spy.method())./*...*/. is lazy? Like do..while loop ?

我找不到有关的文档

推荐答案

关于此语法,您应该注意一件事:

One thing you should notice about this syntax:

when(spy.method()).thenAnswer(someAnswer);

Java在评估它时要做的第一件事就是运行:

Is that the first thing Java will do when evaluating it is to run:

     spy.method()

...以便它可以将准确的返回值传递给when方法.当然,when放弃其参数,仅读取对模拟的最后一次调用,但是Java无法从语法中得知这一点.对于第一次在模拟中调用when的方法,该方法应该没有异常或副作用,但是该假设不适用于间谍或已被存根的方法.

...so that it can pass an accurate return value into the when method. Of course, when discards its parameter and just reads the last call to a mock, but Java can't know that from the syntax. For the very first call to when on a mock, the method should have no exceptions or side effects, but that assumption doesn't hold on spies or on methods that you've already stubbed.

一般来说,doAnswer和其他doVerb方法有两个主要用途:取消无效方法覆盖已定义的行为(例如,对于间谍和已经-存根的方法).

In general, doAnswer and other doVerb methods have two key uses: stubbing void methods and overriding already-defined behavior (i.e. for spies and already-stubbed methods).

无效方法

// Doesn't work: voidMethod has no return value, so when() has no parameter
when(yourMock.voidMethod()).thenThrow(new RuntimeException());
// This works, because it skips reading the voidMethod return value:
doThrow(new RuntimeException()).when(yourMock).voidMethod();

已经存根的方法

// Doesn't work: This contains a call to dangerousMethod!
when(yourSpy.dangerousMethod()).thenReturn(safeValue);
// This works, because the call to dangerousMethod happens on a dummy copy of yourSpy:
doReturn(safeValue).when(yourSpy).dangerousMethod();

lkrnac的答案所述,Mockito在侦听顶级Mockito文档中的重要陷阱!.

As noted in lkrnac's answer, Mockito describes this latter case in the "important gotcha on spying real objects!" in top-level Mockito documentation.

这篇关于在mockito中执行doAnswer-何时进行惰性评估,何时进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆