[英]mock object to return a real object with same arguments
I'm trying to mock a factory. 我正试图嘲笑一家工厂。 In this example, this factory has a method create
which takes two args and return a C object with has a constructor which takes same two args. 在这个例子中,这个工厂有一个方法create
,它接受两个args并返回一个C对象,它有一个带有相同两个args的构造函数。 I'd like to setup my factory to when I order my factory to create a new C, it returns a real new C with given args to create
method. 我想设置我的工厂,当我命令我的工厂创建一个新的C时,它返回一个带有给定args的真正的新C来create
方法。
Mockito.when(myFactory.create(Mockito.any(A.class), Mockito.any(B.class)))
.thenReturn(new C(??, ??));
How can I achieve this? 我怎样才能做到这一点? Any help will be appreciated 任何帮助将不胜感激
Use doAnswer
to capture and use the parameters passed to the mocked factory call. 使用doAnswer
捕获并使用传递给doAnswer
工厂调用的参数。
For example: 例如:
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)));
Try this: 试试这个:
MyFactory myFactory = mock(MyFactory.class);
A a = new A();
B b = new B();
doReturn(new C(a, b)).when(myFactory).create(eq(a), eq(b));
Just import eq method from hamcrest. 只需从hamcrest导入eq方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.