1

我正在尝试像这样使用 PowerMock 模拟私有方法

BalanceResponseGenerator balanceResponseGenerator = spy(new BalanceResponseGenerator());
when(balanceResponseGenerator, "getBalance",client.getParent(), request.getTerminal().getRetailPoint().getRetailNetwork(), result).thenReturn(new Balance());

但是调用了真正的方法,为什么会这样呢?怎么了?我看到了几个例子,它们都对我不起作用。请解释!

4

1 回答 1

0

我想问题是你的 when 调用是在 Mockito.when(..) 上调用的。PowerMockito.when(..)

文档中给出了适当的示例

@RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
    @Test
    public void privatePartialMockingWithPowerMock() {        
        PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());

        // use PowerMockito to set up your expectation
        PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");

        // execute your test
        classUnderTest.execute();

        // Use PowerMockito.verify() to verify result
        PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
    }
}
于 2013-06-18T11:24:07.413 回答