前言
本篇文章將說明如何使用PowerMock
對私有方法進(jìn)行Mock
。關(guān)于使用PowerMock
需要引入哪些依賴,請參考PowerMock使用-依賴準(zhǔn)備。
正文
被測試類如下所示。
public class MockPrivateMethod {
public boolean isTrue() {
return returnTrue();
}
private boolean returnTrue() {
return true;
}
}
被測試類中有一個公共方法isTrue()
,在isTrue()
方法中會調(diào)用MockPrivateMethod
的私有方法returnTrue()
。測試類如下所示。文章來源:http://www.zghlxwxcb.cn/news/detail-504624.html
@RunWith(PowerMockRunner.class)
@PrepareForTest(MockPrivateMethod.class)
public class PowerMockTest {
@Test
public void mockPrivate() throws Exception {
MockPrivateMethod mockPrivateMethod = PowerMockito.mock(MockPrivateMethod.class);
PowerMockito.when(mockPrivateMethod, "returnTrue").thenReturn(false);
PowerMockito.when(mockPrivateMethod.isTrue()).thenCallRealMethod();
assertThat(mockPrivateMethod.isTrue(), is(false));
}
}
Mock
私有方法打樁時,需要使用PowerMockito.when(mock實例, "私有方法名").thenReturn(期望返回值)
的形式設(shè)置mock實例的私有方法的返回值,如果私有方法有參數(shù),還需要在私有方法名后面添加參數(shù)占位符,比如PowerMockito.when(mock實例, "私有方法名", anyInt()).thenReturn(期望返回值)
。上面例子中進(jìn)行斷言時,調(diào)用私有方法采取了調(diào)用公共方法來間接調(diào)用私有方法的形式,單元測試代碼對業(yè)務(wù)代碼造成了入侵,因此如果僅僅只是為了驗證一個私有方法,可以使用Whitebox
來方便的調(diào)用私有方法,如下所示。文章來源地址http://www.zghlxwxcb.cn/news/detail-504624.html
public class MockPrivateMethod {
private boolean returnTrue() {
return true;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(MockPrivateMethod.class)
public class PowerMockTest {
@Test
public void mockPrivate() throws Exception {
MockPrivateMethod mockPrivateMethod = PowerMockito.mock(MockPrivateMethod.class);
PowerMockito.when(mockPrivateMethod, "returnTrue").thenReturn(false);
assertThat(Whitebox.invokeMethod(mockPrivateMethod, "returnTrue"),
is(false));
}
}
到了這里,關(guān)于PowerMock使用-Mock私有方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!