UnsyncFilterOutputStream extends OutputStream { @Override public void close() throws IOException { try (OutputStream os = outputStream) { flush(); } } UnsyncFilterOutputStream(OutputStream outputStream); @Override void close(); @Override void flush(); @Override void write(byte[] bytes); @Override void write(byte[] bytes, int offset, int length); @Override void write(int b);  }
@Test public void testClose() throws IOException { AtomicBoolean closeCalled = new AtomicBoolean(); AtomicBoolean flushCalled = new AtomicBoolean(); UnsyncFilterOutputStream unsyncFilterOutputStream = new UnsyncFilterOutputStream( new TestOutputStream() { @Override public void close() { closeCalled.set(true); } @Override public void flush() { flushCalled.set(true); } }); unsyncFilterOutputStream.close(); Assert.assertTrue(closeCalled.get()); Assert.assertTrue(flushCalled.get()); }
@Test(expected = NullPointerException.class) public void testCloseNull() throws IOException { UnsyncFilterOutputStream unsyncFilterOutputStream = new UnsyncFilterOutputStream(null); unsyncFilterOutputStream.close(); }
@Test public void testCloseWithException() throws IOException { IOException ioException1 = new IOException(); AtomicBoolean closeCalled = new AtomicBoolean(); UnsyncFilterOutputStream unsyncFilterOutputStream = new UnsyncFilterOutputStream( new TestOutputStream() { @Override public void close() { closeCalled.set(true); } @Override public void flush() throws IOException { throw ioException1; } }); try { unsyncFilterOutputStream.close(); Assert.fail(); } catch (IOException ioException2) { Assert.assertSame(ioException1, ioException2); } Assert.assertTrue(closeCalled.get()); }
@Test public void testCloseWithTwoExceptions() throws IOException { IOException ioException1 = new IOException(); IOException ioException2 = new IOException(); UnsyncFilterOutputStream unsyncFilterOutputStream = new UnsyncFilterOutputStream( new TestOutputStream() { @Override public void close() throws IOException { throw ioException2; } @Override public void flush() throws IOException { throw ioException1; } }); try { unsyncFilterOutputStream.close(); Assert.fail(); } catch (IOException ioException3) { Assert.assertSame(ioException1, ioException3); Throwable[] throwables = ioException1.getSuppressed(); Assert.assertEquals( Arrays.toString(throwables), 1, throwables.length); Assert.assertSame(ioException2, throwables[0]); } }