1

我想模拟一个静态方法以及一个类的非静态方法。我的来源看起来像:

    public class XDSUtilityManager
    {
private static XDSUtilityManager xdsUtilMgr = new XDSUtilityManager(); private XDSUtilityManager() { xdsUtilMgrImpl = new XDSUtilityManagerImpl(); }
public static XDSUtilityManager getInstance() { return (xdsUtilMgr == null ) ? new XDSUtilityManager() : xdsUtilMgr; } public XMLDocument getXMLDocument(final String absoluteKey, final XDSClient xdsClient) { return getXMLDocument(absoluteKey, xdsClient, false); } }

我想模拟静态方法getInstance()。我希望 getInstance() 返回XDSUtilityManager类的模拟对象。我还想模拟不是静态的getXMLDocument() 。

在我的测试用例中,我尝试了以下操作:

XMLDocument xmlDocument = PowerMock.createMock(XMLDocument.class);
XDSUtilityManager xdsUtilityManager = PowerMock.createPartialMock(XDSUtilityManager.class,"getXMLDocument");
PowerMock.mockStaticPartial(XDSUtilityManager.class, "getInstance"); expect(XDSUtilityManager.getInstance()).andReturn(xdsUtilityManager).anyTimes();
expect(xdsUtilityManager.getXMLDocument((String)anyObject(), anyObject(XDSClient.class))).andReturn(xmlDocument).anyTimes();
PowerMock.replay(xdsUtilityManager); PowerMock.replay(xmlDocument);

但事情并没有按预期工作。请帮忙

4

2 回答 2

7

我发现最简单的方法是使用PowerMockito。PowerMockito 是 Mockito 和 PowerMock 的组合,它允许模拟静态对象。

我使用的模式是使用你的静态模拟getInstance()来返回你的非静态模拟的副本,然后你可以正常扩展它。使用PowerMockito的示例是:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SingletonObject.class})
public class SingletonTester {
  @Mock
  private SingletonObject singleMock;

  @Before
  public void setup(){
      // initialize all the @Mock objects
      MockitoAnnotations.initMocks(this);
      // mock all the statics
      PowerMockito.mockStatic(SingletonObject.class);
  }

  @Test
  public void mockTester(){
      // Mock the static getInstance call to return the non-Static Mock
      Mockito.when(SingletonObject.getInstance()).thenReturn(singleMock);

      // Mock the non static version as normal
      PowerMockito.when(singleMock.nonStaticMethodCall()).thenReturn("Whatever you need.");
      //..........
  }
}

您获取单例对象的静态调用getInstance()返回您还定义的实例化模拟对象。一旦你告诉静态返回什么,你就可以像往常一样继续模拟非静态调用。

于 2013-03-19T20:24:33.813 回答
1

它不需要调用getInstance()方法来创建XDSUtilityManager. 使用PowerMockito,因为您的构造函数是私有的,您需要suppress the constructor在调用 create mock 之前,如下所示..

PowerMockito.suppress(PowerMockito.constructor(XDSUtilityManager.class));
// enable static mocking for all the methods in the class   
PowerMockito.mockStatic(XDSUtilityManager.class); 
XDSUtilityManager xDSUtilityManager =  PowerMockito.mock(XDSUtilityManager.class);
XMLDocument xmlDocument = PowerMock.createMock(XMLDocument.class); 
PowerMockito.when(xDSUtilityManager.getXMLDocument(
    Mockito.anyString(),Mockito.anyObject())).thenReturn(xmlDocument);
于 2013-06-07T14:16:40.610 回答