2014-09-29 16 views
0

如果我正在爲Singleton類編寫單元測試,那麼我該如何去模擬Singleton類的私有方法。因爲我要找的情景示例代碼片段如下: -如果類本身正在使用PowerMock進行測試,如何模擬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;} 
} 

我如何可以模擬方法2.要想在上面的例子中,測試方法1?

+1

爲什麼你需要爲了測試方法1嘲笑方法2? – clD 2014-09-29 11:41:20

+0

我是單元測試新手。我認爲,爲了測試方法1,我將不得不創建一個虛擬方法2,以便不發生對實際方法2的調用。如果我的方法不正確,請告訴我應該怎麼做單元測試方法1? – Siddharth 2014-09-29 14:39:03

回答

1

要測試method1您只需要像測試其他方法一樣測試它。在這種情況下,被測對象Singleton類不應該被模擬。

通常在設置方法,然後創建測試(測試對象)測試對象即類:

@Test 
public void testMethod1() { 
    int testValue = 1;  
    int expectedResult = 2; 

    assertThat(testee.method1(testValue), equalTo(expectedResult)); 
} 

在上面的例子中,我會用參數化測試的東西,如JUnitParams到例如測試界限,整數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,在這種情況下,辛格爾頓從其他組件(合作者)隔離,以確保正確的行爲。在這種情況下,這是沒有必要的。

時,你可以使用一個模擬

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)); 
} 
+0

感謝您的回答。因此,我是否認爲對某個方法(此處爲method1)的測試可以調用同一類的其他私有方法(此處爲方法2)。我這樣說是因爲「assertThat(testee.method1(testValue),equalTo(expectedResult));」也會對method2進行實際調用。 – Siddharth 2014-09-30 06:11:53

+0

是的,不建議模擬私人方法。另外調用'method2'的'method1'允許你測試私有方法的行爲。雖然在大多數情況下私人方法的意見問題不是直接測試,而是通過公共API進行測試。這裏有關於測試私有方法的很好的討論。 http://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones – clD 2014-09-30 08:13:09

+0

感謝您的回答。 – Siddharth 2014-09-30 08:34:20

相關問題