简体   繁体   English

Mockito + Spy:如何收集返回值

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

I got a class using a factory for creating some object.我有一个 class 使用工厂来创建一些 object。 In my unit test I would like to access the return value of the factory.在我的单元测试中,我想访问工厂的返回值。 Since the factory is directly passed to the class and no getter for the created object is provided I need to intercept returning the object from the factory.由于工厂直接传递给 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.

Is there a possibility to access the return value of the factory?是否有可能访问工厂的返回值? Probably using the spy?可能使用间谍?
The only way I can see is to mock the factory create method.我能看到的唯一方法是模拟工厂创建方法。

First thing, you should be passing spy in as the constructor argument.首先,您应该将spy作为构造函数参数传入。

That aside, here's how you could do it.除此之外,这就是你如何做到的。

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;
    }
}

Intended usage:预期用途:

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);

The standard mocking approach would be to:标准的 mocking 方法是:

  1. Pre-create the object you want the factory to return in the test case在测试用例中预先创建您希望工厂返回的 object
  2. Create a mock (or spy) of the factory创建工厂的模拟(或间谍)
  3. Prescribe the mock factory to return your pre-created object.规定模拟工厂返回您预先创建的 object。

If you really want to have the RealFactory create the object on the fly, you can subclass it and override the factory method to call super.create(...) , then save the reference to a field accessible by the test class, and then return the created object.如果您真的想让 RealFactory 即时创建 object,您可以对其进行子类化并重写工厂方法以调用super.create(...) ,然后将引用保存到测试 class 可访问的字段,然后返回创建的 object。

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

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