2017-06-21 109 views
3

所以我想在一個有靜態方法的方法上使用Mockito。原因是我無法使用PowerMock,因此我使用非靜態方法封裝了該方法。如何正確使用Mockito靜態方法包裝在非靜態方法中?

public class WrapperUtil { 

    public String getURLContent(String path) throws IOException{ 
     URL url = new URL(path); 
     return IOUtils.toString(url); 
    } 
} 

現在我用兩種不同的方式測試了WrapperUtil類。一個測試工作,但沒有提供任何WrapperUtil類的覆蓋,另一個是拋出一個空指針異常相關的靜態方法。

這是一個工程,但沒有提供任何報道。

@RunWith(MockitoJUnitRunner.class) 
public class WrapperUtilTest { 

    @InjectMocks 
    WrapperUtil ioutils; 


    @Before 
    public void setUp() throws Exception { 

     ioutils = new WrapperUtil(); 
    } 

    @Test 
    public void testGetUrlContent() throws IOException { 

     WrapperUtil ioutilsSpy = Mockito.spy(ioutils); 
     Mockito.doReturn("test").when(ioutilsSpy).getURLContent(Mockito.anyString()); 
     assertTrue(ioutils2.getURLContent("test").contains("test")); 

    } 

} 

這是一個不工作:

@RunWith(MockitoJUnitRunner.class) 
public class WrapperUtilTest { 

    @InjectMocks 
    WrapperUtil ioutils; 


    @Before 
    public void setUp() throws Exception { 

     ioutils = new WrapperUtil(); 
    } 

    @Test 
    public void testGetUrlContent() throws IOException { 

     WrapperUtil ioutilsSpy = Mockito.spy(ioutils); 
     Mockito.when(ioutilsSpy).getURLContent(Mockito.anyString()).thenReturn("test"); 
     assertTrue(ioutils2.getURLContent("test").contains("test")); 

    } 

} 

我怎樣才能使這項工作,並實現代碼覆蓋,而不使用PowerMockito?非常感謝你的幫助。

+0

無關:您的代碼示例中出現拼寫錯誤。你聲明'ioutils' - 但是你使用'ioutils2'。 – GhostCat

+0

除了那個不清楚的地方:很好的第一個問題。我特別喜歡你的態度,以達到高品質(儘管我的答案在這裏有不同的方向)**和**你的理解,你想避免PowerMock。我希望我能再次爲你贏得三次勝利! – GhostCat

+0

最後,再次無關:假設您正在使用Apache IOUtils.toString() - 請注意,此方法*棄用*,您應該使用取代編碼的方法! – GhostCat

回答

1

我的兩個百分之這裏:

  • 我甚至會走一步,定義一個接口表示功能
  • 在另一方面,我也不會去「落水」測試包裝實施

要點是:只有一點點膠水代碼在這裏。如果您能夠測試此代碼來驗證此膠水代碼的作品 - 那麼你很好。

換句話說:避免掛上100%的覆蓋率!覆蓋範圍是工具,設計爲幫助您實現代碼質量。

100%覆蓋範圍不是導致「100%代碼質量」!

通過嘗試「始終做正確的事情」來實現代碼質量。

在這裏,「正確的事情」是不爭取100%的覆蓋面。

因爲我猜你不會在沒有轉向PowerMock(ito)的情況下達到這個目標。而且,避免PowerMock(ito)本身就是一件好事 - 我的建議是:簡單地接受你無法達到100%的覆蓋率。

如果有的話,我會花我的時間試圖排除這個類從覆蓋運行。