1 // Copyright (C) 2004, 2014 Christian Jaekl
3 package net.jaekl.qd.util;
5 import java.io.Closeable;
6 import java.io.IOException;
8 import junit.framework.Assert;
9 import net.jaekl.qd.QDException;
11 import org.junit.Test;
13 public class ExceptionUtilsTest {
15 private static class CloseableMock implements Closeable
17 private IOException m_exception;
18 private int m_timesClosed;
20 public CloseableMock() {
25 public int getTimesClosed() { return m_timesClosed; }
26 public void setExceptionToThrow(IOException ioe) { m_exception = ioe; }
29 public void close() throws IOException {
31 if (null != m_exception) {
32 throw new IOException("This is a test");
37 // Try closing a closeable.
38 // It should be closed (once only).
40 public void test_tryClose_success() throws QDException
42 CloseableMock cm = new CloseableMock();
44 ExceptionUtils.tryClose(cm);
45 Assert.assertEquals(1, cm.getTimesClosed());
48 // Try closing a closeable that throws an IOException
50 public void test_tryClose_exception() throws QDException
52 final String MESSAGE = "This is a test";
54 CloseableMock cm = new CloseableMock();
55 cm.setExceptionToThrow(new IOException(MESSAGE));
58 ExceptionUtils.tryClose(cm);
60 catch (QDException qde) {
61 Assert.assertNotNull(qde);
62 Throwable t = qde.getCause();
63 Assert.assertNotNull(t);
64 Assert.assertTrue(t instanceof IOException);
65 Assert.assertEquals(MESSAGE, t.getMessage());
69 // Try closing a null pointer.
70 // This should be harmless (no exception thrown).
72 public void test_tryClose_null() throws QDException
74 ExceptionUtils.tryClose(null);