简体   繁体   中英

AssertThrows not throwing exception when going through Java Streams

So I'm writing unit tests in which I'm testing capability to blacklist and unblacklist users (which is a feature in my code that is itself working fine).

Here's a sample command that works as expected:

assertThrows(ExecutionException.class, () -> onlineStore.lookup("533"));

If I blacklist user "533", and then run the above command, it works fine, because an ExecutionException is raised (because you're trying to lookup a user who is blacklisted). Similarly, if I had NOT blacklisted user "533" but still ran the above command, the test would fail, which is expected too for similar reason (ie no exception is now thrown as you're NOT fetching a blacklisted user).

However if I have a List of user IDs called userIds (which user "533" is now part of) and I blacklist them all (funtionality which I know is working fine), and then run the command below:

userIds.stream().map(id -> assertDoesNotThrow(() -> onlineStore.lookup(id)));

... the test passes, even through it should have FAILED. Why ? Because all users are now blacklisted, so when fetching these users, ExecutionExceptions should have been thrown ..

If I now, replace the streams command above with either of the following, they work as expected:

assertThrows(ExecutionException.class, () -> onlineStore.lookup("533"));

assertDoesNotThrow(() -> onlineStore.lookup("533"));

So this all leads me to believe that for some reason, when going through Java Streams, thrown ExecutionExceptions aren't getting caught.

Any explanation for this behavior ?

You're not calling any terminal operation on the stream, so your assertion is never executed.

You're abusing map() , which is supposed to create a new stream by transforming every element. What you actually want to do is to execute a method which has a side effect on every element. That's what forEach is for (and it's also a terminal operation which actually consumes the stream):

 userIds.stream().forEach(id -> assertDoesNotThrow(() -> onlineStore.lookup(id)));

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