我有一个静态方法,我需要使用Mockito / PowerMockito进行模拟
Public static Person MyFactory.getPersonObject(Info info)
这个方法正在循环中使用,并且对于每个Person
,创建了Info
瞬间。
Info
是Person
的数据成员。
For(int i = 0; i< SIZE; i++) {
Info info = getTheInfo(i);
Person person = MyFactory.getPersonObject(info);
………
………
}
我的问题是如何每次使用Info
实例。我不能在我的嘲笑中使用getTheInfo(int)
。
这是我到目前为止所得到的:
PowerMockito.mockStatic(MyFactory.class);
PowerMockito.when(MyFactory.getPersonObject (Mockito.any(Info.class)).thenReturn( /*Person with its info instance*/);
Mockito.any(Info.class)
应该在运行时用正确的Info
实例替换,所以可能我没有使用正确的方法。
Mockito / PowerMockito支持吗?
谢谢
这应该工作。
ArgumentCaptor<Info> argumentCaptor = ArgumentCaptor.forClass(Info.class);
doAnswer(invocation-> {
Info info = argumentCaptor.getValue();
/* check for some property of info and based on that return different instances of person object*/
if(...) {
return person1
}
else if (....) {
return person2
}
....
}).when(MyFactory).getPersonObject(argumentCaptor.capture());