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. 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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.