Mockito + Spy:如何收集返回值

2022-09-01 21:42:08

我得到了一个使用工厂创建一些对象的类。在我的单元测试中,我想访问工厂的返回值。由于工厂直接传递给类,并且没有提供所创建对象的getter,因此我需要拦截从工厂返回的对象。

RealFactory factory     = new RealFactory();
RealFactory spy         = spy(factory);
TestedClass testedClass = new TestedClass(factory);

// At this point I would like to get a reference to the object created
// and returned by the factory.

是否有可能访问工厂的返回值?可能使用间谍?
我能看到的唯一方法是模拟工厂创建方法。


答案 1

首先,您应该作为构造函数参数传入。spy

除此之外,这是你如何做到这一点。

public class ResultCaptor<T> implements Answer {
    private T result = null;
    public T getResult() {
        return result;
    }

    @Override
    public T answer(InvocationOnMock invocationOnMock) throws Throwable {
        result = (T) invocationOnMock.callRealMethod();
        return result;
    }
}

预期用途:

RealFactory factory     = new RealFactory();
RealFactory spy         = spy(factory);
TestedClass testedClass = new TestedClass(spy);

// At this point I would like to get a reference to the object created
// and returned by the factory.


// let's capture the return values from spy.create()
ResultCaptor<RealThing> resultCaptor = new ResultCaptor<>();
doAnswer(resultCaptor).when(spy).create();

// do something that will trigger a call to the factory
testedClass.doSomething();

// validate the return object
assertThat(resultCaptor.getResult())
        .isNotNull()
        .isInstanceOf(RealThing.class);

答案 2

标准的嘲弄方法是:

  1. 在测试用例中预先创建希望工厂返回的对象
  2. 创建工厂的模拟(或间谍)
  3. 指定模拟工厂以返回预先创建的对象。

如果您真的想让 RealFactory 动态创建对象,则可以对其进行子类化并重写要调用的 factory 方法,然后保存对测试类可访问的字段的引用,然后返回创建的对象。super.create(...)


推荐