繁体   English   中英

Mockito + Spy:如何收集返回值

[英]Mockito + Spy: How to gather return values

我有一个 class 使用工厂来创建一些 object。 在我的单元测试中,我想访问工厂的返回值。 由于工厂直接传递给 class 并且没有为创建的 object 提供吸气剂,因此我需要拦截从工厂返回的 object。

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.

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

首先,您应该将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);

标准的 mocking 方法是:

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

如果您真的想让 RealFactory 即时创建 object,您可以对其进行子类化并重写工厂方法以调用super.create(...) ,然后将引用保存到测试 class 可访问的字段,然后返回创建的 object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM