[英]How to test void using Unit Test?
我有以下方法,並為此方法用 Java 編寫了一個單元測試。 除了if
語句之外,它被覆蓋,我還需要測試這部分。
@InjectMocks
private ProductServiceImpl productService;
public void demoMethod(final List<UUID> productUuidList) {
if (productUuidList.isEmpty()) {
return;
}
final Map<ProductRequest, PriceOverride> requestMap = getPriceRequests(uuidList);
productService.updateByPriceList(priceRequestMap, companyUuid);
}
但是,由於方法執行已完成並且在uuidList
為空時不返回任何內容,因此我無法測試此if
塊。
所以:
if
阻止,我該如何測試?
我應該創建一個新的單元測試方法來測試這個if
塊嗎? 或者我應該將相關的斷言行添加到當前的測試方法中嗎?
更新:這是我的測試方法:
@Test
public void testDemoMethod() {
final UUID uuid = UUID.randomUUID();
final List<Price> priceList = new ArrayList<>();
final Price price = new Price();
price.setUuid(uuid);
priceList.add(price);
productService.demoMethod(Collections.singletonList(uuid));
}
一般的想法是你不想測試特定的代碼,但你想測試一些行為。
因此,在您的情況下,您希望驗證在傳入空List
時不會調用getPriceRequests
和priceService.updateByPriceList
。
具體如何執行取決於您可用的工具。 最簡單的方法是,如果您已經模擬priceService
:那么只需指示您的模擬庫/框架驗證從未調用updateByPriceList
。
在 if 條件中返回的要點是不執行其余代碼。 即,如果要執行此// code omitted for brevity
,則該方法將無法滿足其目的。 因此,只要確保無論該代碼做什么,如果您的列表為空,它就沒有完成。
你有3個選擇:
查看測試金字塔和 貧血架構如何破壞您的測試以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.