[英]What is wrong with partial mocking in this case?
假設我有兩種方法,其中一種基本上是另一種方法的包裝,只需要一點點額外的處理即可:
public class ItemRepositoryImpl implements ItemRepository {
...
@Override
public void delete(UUID itemID) {
Item item = findOne(itemID);
delete(item);
}
@Override
public void delete(Item item) {
// Do a bunch of stuff that needs a lot of tests run on it, like
// deleting from multiple data sources etc
...
}
}
為為部分模擬ItemRepositoryImpl的delete(UUID)方法編寫單元測試並檢查該delete(UUID)最終調用delete(Item)有什么問題? 如果這樣做,則不必為每個刪除方法編寫一堆重復的測試!
在Mockito中,我可以用這樣的間諜來實施這樣的測試:
ItemRepository spyRepo = spy(repository); // Create the spy
when(spyRepo.findOne(itemID)).thenReturn(item); // Stub the findOne method
doNothing().when(spyRepo).delete(item); // Stub the delete(Item) method
spyRepo.delete(itemID); // Call the method under test
// Verify that the delete(Item) method was called
verify(spyRepo).delete(item);
但是,Mockito文檔強烈建議不要使用這種類型的部分模擬,基本上是說只能在臨時舊版代碼和第三方API中使用。 有什么更好的解決方案?
如果您正在執行純單元測試,而您的測試單元是一種方法,那么我想說您在這里模擬的內容沒有錯。 有人會認為單元測試應該采用更黑盒的方法,並且通過模擬方法調用,您的測試對被測方法的實現了解得太多了。
如果被測單元是類而不是方法,那么您可以簡單地模擬對其他類的調用。
關於單元測試總是有爭論。 這是一篇與您的問題非常相關的有趣文章: http : //martinfowler.com/articles/mocksArentStubs.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.