PowerMock - IllegalStateException: Must replay Cla

2019-05-27 01:10发布

问题:

@PrepareForTest({...,..., XXX.class})
...
@Test
public void testMethodToBeTested(){
    XXX mockInstance = PowerMock.createMock(XXX.class); 
    ...
    PowerMock.expectNew(XXX.class, p1, p2, p3, p4, p5).andReturn(mockInstance);
    mockInstance.methodWithNoReturnVal();
    expect(mockInstance.getSearchVal()).andReturn(1);
    PowerMock.replay(mockInstance);
    Whitebox.invokeMethod(objInstance, "methodToBeTested");

    PowerMock.verify(mockInstance);
}

Essentially, I want to test a private method: methodToBeTested(). This method instantiates an object (using the new operator) of type XXX.class and stores it into an instance variable; I mocked this object. Then, it calls methodWithNoReturnVal() via the mock, and then a getter method which I configured to return 1.

I get the error "IllegalStateException: Must replay class XXX.class to get configured expectation."

Any help is appreciated. I am still new to PowerMock and EasyMock; since I needed to use the expectNew(...) method, I made sure to use all PowerMock api inside of the test method.

回答1:

You need to have a PowerMock.replay(XXX.class); in the method for Powermock to intercept the construction of the object. See below.

@PrepareForTest({...,..., XXX.class})
...
@Test
public void testMethodToBeTested(){
    XXX mockInstance = PowerMock.createMock(XXX.class); 
    ...
    PowerMock.expectNew(XXX.class, p1, p2, p3, p4, p5).andReturn(mockInstance);
    mockInstance.methodWithNoReturnVal();
    expect(mockInstance.getSearchVal()).andReturn(1);
    PowerMock.replay(mockInstance, XXX.class);
    Whitebox.invokeMethod(objInstance, "methodToBeTested");

    PowerMock.verify(mockInstance);
}


回答2:

This might be an open issue in PowerMock.

Check http://code.google.com/p/powermock/issues/detail?id=271&q=IllegalStateException for more details.