[英]Java spock - how to test catch() block that doesnt throw exception back
[英]How to unit test a catch block which does not throw any exception
這是我的代碼。
@Override
public KinesisEvent handleRequest(@NonNull KinesisEvent kinesisEvent, @NonNull Context context) {
KinesisEvent kinesisEventReturn = kinesisEvent.clone();
final List<KinesisEvent.KinesisEventRecord> transformedRecords = kinesisEventReturn.getRecords().stream().map(
record -> {
try {
return decryptLog(record);
} catch (IOException e) {
log.error("Decryption did not work. See exception: ", e);
}
return record;
}).collect(Collectors.toList());
kinesisEventReturn.setRecords(transformedRecords);
return kinesisEventReturn;
}
如果你看到了,我有一個 catch 塊,它捕獲異常但不拋出異常。 我想在單元測試中測試 catch 塊。 但是我找到的所有示例都是測試是否拋出異常。
如果有任何解決方法,請提供幫助。
謝謝德魯博
您的 function 逐步通過集合(流),嘗試解密每個記錄,並生成它返回的每個解密記錄的列表。 如果解密失敗,則會生成日志消息並將原始記錄添加到列表中。
您可以使用如果執行 catch 塊,則 kinesisEventReturn.getRecords() 的成員將在返回列表中的事實。 因此,您的測試用例需要構造已知會導致decryptLog(record)
拋出IOException
的輸入。
當一個IOException
被拋出/捕獲時, function 的結果將至少有一個來自輸入Collection
的成員。 您可以使用Collections.disjoint來簡化該測試:
if (! Collections.disjoint(result, kinesisEventReturn.getRecords()) {
// Test failed
假設解密的記錄總是不同於加密的記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.