java Mockito + Spy:如何收集返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7095871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito + Spy: How to gather return values
提问by Marc-Christian Schulze
I got a class using a factory for creating some 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.
我得到了一个使用工厂来创建一些对象的类。在我的单元测试中,我想访问工厂的返回值。由于工厂直接传递给类,并且没有为创建的对象提供 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.
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...
是否有可能访问工厂的返回值?可能使用间谍?
我能看到的唯一方法是模拟工厂创建方法......
Regards
问候
回答by Jeff Fairley
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);
回答by oksayt
The standard mocking approach would be to:
标准的模拟方法是:
- Pre-create the object you want the factory to return in the test case
- Create a mock (or spy) of the factory
- Prescribe the mock factory to return your pre-created 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 动态创建对象,您可以将其子类化并覆盖工厂方法以调用super.create(...)
,然后保存对测试类可访问的字段的引用,然后返回创建的对象。