[英]How to mock another class method call from the method being tested using powermock-easymock?
[英]How to mock private method of a Singleton class if the class is itself being tested using PowerMock?
如果我正在為Singleton類編寫單元測試,那么我該如何模擬Singleton類的私有方法。 我正在尋找的場景的示例代碼片段如下:-
Class Singleton {
private static Singleton instance = new Singleton();
protected Singleton() {}
public Singleton synchronized getInstance() { return instance;}
public int method1(int a) {
int ret = method2(a);
return ret;
}
private int method2(int num) { return num + 1;}
}
如何在上面的示例中模擬method2以測試method1?
要測試method1
您只需要像其他方法一樣對其進行測試。 在這種情況下,不應模擬被測對象的Singleton類。
通常使用設置方法創建一個測試對象,即您的被測類(被測者),然后:
@Test
public void testMethod1() {
int testValue = 1;
int expectedResult = 2;
assertThat(testee.method1(testValue), equalTo(expectedResult));
}
在上面的示例中,我將對JUnitParams等參數進行參數化測試來測試邊界,例如Integer MAX_VALUE等。
@Test
@Parameters(method = "method1Params")
public void testMethod1(int testValue, int expectedResult) {
assertThat(testee.method1(testValue), equalTo(expectedResult));
}
@Ignore
private final Object[] method1Params() {
return new Object[] {
new Object { 1, 2 },
new Object { -2, -1 }
};
}
模擬主要用於要測試SUT的情況,在這種情況下,Singleton與其他組件(協作者)隔離以確保其行為正常。 在這種情況下,沒有必要。
什么時候可以使用模擬
public int method1(DependedOnComponent doc) {
int a = 1;
int ret = doc.method2(a);
return ret;
}
然后
@Test
public void testMethod1() {
DependedOnComponent mockDOC = mock(DependedOnComponent.class);
// When method2() is called you control the value returned
when(mockDOC.method2(1)).thenReturn(2);
assertThat(testee.method1(mockDOC), equalTo(2));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.