Mockito / PowerMockito每次在不同实例的循环中模拟静态方法?

问题描述 投票:0回答:1

我有一个静态方法,我需要使用Mockito / PowerMockito进行模拟

Public static Person MyFactory.getPersonObject(Info info)

这个方法正在循环中使用,并且对于每个Person,创建了Info瞬间。

InfoPerson的数据成员。

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支持吗?

谢谢

java mockito powermock powermockito
1个回答
0
投票

这应该工作。

   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());
© www.soinside.com 2019 - 2024. All rights reserved.