Reputation: 3162
I have a java 8 stream with underlying IOStream and I want to make sure that my method closes that stream.
Is there any way to check it with unit test?
Upvotes: 3
Views: 2411
Reputation: 185
I think providing a handler to Stream's onClose
method is the easiest way to do this.
AtomicBoolean wasClosed = new AtomicBoolean(false);
Stream<> stream = Stream.of(foo, bar).onClose(() -> wasClosed.set(true));
// ...code under test that uses the stream
assertThat(wasClosed.get()).isTrue();
For what it's worth, I legitimately needed to test this, as we make Streams from JDBC ResultSets, and the actual Stream relies on onClose to close the ResultSet.
Upvotes: 3
Reputation: 2284
Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
Upvotes: -1