我正在尝试模拟工厂。在此示例中,该工厂有一个方法 create
,它接受两个参数并返回一个 C 对象,该对象具有一个接受相同两个参数的构造函数。我想将我的工厂设置为当我命令我的工厂创建一个新的 C 时,它返回一个带有给定参数的真正的新 C 到 create
方法。
Mockito.when(myFactory.create(Mockito.any(A.class), Mockito.any(B.class)))
.thenReturn(new C(??, ??));
我怎样才能做到这一点?任何帮助将不胜感激
最佳答案
使用doAnswer
捕获并使用传递给模拟工厂调用的参数。
例如:
MyFactory myFactory = mock(MyFactory.class);
Answer<C> answer = new Answer<C>() {
public C answer(InvocationOnMock invocation) throws Throwable {
A a = invocation.getArgument(0, A.class);
B b = invocation.getArgument(1, B.class);
return new C(a, b);
}
};
// either of these ...
when(myFactory.create(Mockito.any(A.class), Mockito.any(B.class))).thenAnswer(answer);
doAnswer(answer).when(myFactory.create(Mockito.any(A.class), Mockito.any(B.class)));
关于java - 模拟对象返回具有相同参数的真实对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054082/