简体   繁体   中英

How to unit test a catch block which does not throw any exception

Here is my code.

    @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;
    }

If you see, I have catch block which catches exception but not throws the exception. I wanted to test the catch block in unit testing. But all the example i find is to test whether an exception is thrown or not.

Please help if there any work around with that.

Thanks Dhrubo

Your function steps through a Collection (Stream), attempts to decrypt each record, and produces a list of each decrypted record which it returns. If the decryption fails, the log message is generated and the original record is added to list instead.

You can use the fact that the if the catch block is exercised, a member of kinesisEventReturn.getRecords() will be on the returned list. So, your test case requires constructing input known to cause decryptLog(record) to throw an IOException .

When an IOException is thrown/caught, the result of the function will have at least one member from the input Collection . You can use Collections.disjoint to simplify that test:

if (! Collections.disjoint(result, kinesisEventReturn.getRecords()) {
    // Test failed

assuming that decrypted records are always different than encrypted records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM