我使用工厂创建了一个用于创建对象的类。 在我的单元测试中,我想访问工厂的返回值。 由于工厂直接传递给类,并且没有提供创建对象的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.
是否有可能获得工厂的返回值?可能使用间谍?
我能看到的唯一方法是模拟工厂创建方法......
此致
答案 0 :(得分:36)
首先,您应该将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);
答案 1 :(得分:1)
标准的模拟方法是:
如果你真的想让RealFactory动态创建对象,你可以将它子类化并覆盖工厂方法来调用super.create(...)
,然后将引用保存到测试类可访问的字段,然后返回创建的对象。