Mock私有方法与Mockito和PowerMock



我试图用PowerMock模拟私有方法,像这样

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

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

我猜问题是你的何时调用是在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");
    }
}

相关内容

  • 没有找到相关文章

最新更新