2012-12-24 92 views
0

我有方法getAllCustomers裏面的CustomerService類。在這個方法裏面,我調用另一個從CustomerDao類的靜態方法。 現在,當我正在寫方法getAllCustomerscustomerService類,我想嘲笑 靜態方法的CustomerDao,即getAllCustomers的聯繫。以下是 CustomerService類中方法getAllCustomers的簡要代碼片段。 是否可以使用單元模擬靜態方法調用?如何使用UnitilsJUnit4模擬靜態方法?

Public static List<CustomerDate> getAllCustomers() 
{ 
//some operations 
List<CustomerDate> customers=CustomerDao.getAllCustomers();// static method inside CustomerDao 
//some operations 
} 

上面的代碼只是我試圖把一個例子。請避免討論爲什麼這些方法設計爲靜態 方法。這是一個單獨的故事。)

+1

這是一個很好的例子,爲什麼不在TDD環境中使用靜態方法 – Scorpion

回答

0

我懷疑它是否可以用單位實現。 但請考慮使用PowerMock,而不是似乎能夠處理您所需要的。它可以模擬靜態方法,私有方法和更多的(參考文獻:PowerMock

0

這將是一個問題:

  • 設置模擬
  • 調用模擬並期待一些數據回
  • 根據給定的數據驗證呼叫的最終結果

因此,對於靜態調用沒有多少關注,可以在PowerMock中設置它:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(CustomerDao.class) 
public class CustomerTest { 

    @Test 
    public void testCustomerDao() { 
     PowerMock.mockStatic(CustomerDao.class); 
     List<CustomerDate> expected = new ArrayList<CustomerDate>(); 
     // place a given data value into your list to be asserted on later 
     expect(CustomerDao.getAllCustomers()).andReturn(expected); 
     replay(CustomerDao.class); 
     // call your method from here 
     verify(CustomerDao.class); 
     // assert expected results here 
    } 
} 
+0

坦克真實。有沒有辦法在Unitils中做類似的事情? – emilly

+0

我只見過PowerMock。通常避免使某些對象(如此)靜止,因爲它確實使它們稍微難以測試。 – Makoto

相關問題