Mockito + Spy:如何收集返回值

Mar*_*lze 11 java mockito spy

我使用工厂创建了一个用于创建对象的类.在我的单元测试中,我想访问工厂的返回值.由于工厂直接传递给类,并且没有提供创建对象的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.
Run Code Online (Sandbox Code Playgroud)

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

问候

Jef*_*ley 39

首先,你应该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;
    }
}
Run Code Online (Sandbox Code Playgroud)

预期用途:

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);
Run Code Online (Sandbox Code Playgroud)

  • 感谢分享.恕我直言:这应该是公认的答案. (3认同)