Upgrade to Debian Jessie and JDK 7.
[frank.git] / test / net / jaekl / qd / util / ExceptionUtilsTest.java
1 // Copyright (C) 2004, 2014 Christian Jaekl
2
3 package net.jaekl.qd.util;
4
5 import java.io.Closeable;
6 import java.io.IOException;
7
8 import org.junit.Assert;
9 import net.jaekl.qd.QDException;
10
11 import org.junit.Test;
12
13 public class ExceptionUtilsTest {
14
15         private static class CloseableMock implements Closeable 
16         {
17                 private IOException m_exception;
18                 private int m_timesClosed;
19                 
20                 public CloseableMock() {
21                         m_exception = null;
22                         m_timesClosed = 0;
23                 }
24                 
25                 public int getTimesClosed() { return m_timesClosed; }
26                 public void setExceptionToThrow(IOException ioe) { m_exception = ioe; }
27
28                 @Override
29                 public void close() throws IOException { 
30                         m_timesClosed++;
31                         if (null != m_exception) {
32                                 throw new IOException("This is a test");
33                         }
34                 }
35         }
36         
37         // Try closing a closeable.
38         // It should be closed (once only).
39         @Test
40         public void test_tryClose_success() throws QDException
41         {
42                 CloseableMock cm = new CloseableMock();
43                 
44                 ExceptionUtils.tryClose(cm);
45                 Assert.assertEquals(1, cm.getTimesClosed());
46         }
47         
48         // Try closing a closeable that throws an IOException
49         @Test
50         public void test_tryClose_exception() throws QDException
51         {
52                 final String MESSAGE = "This is a test";
53                 
54                 CloseableMock cm = new CloseableMock();
55                 cm.setExceptionToThrow(new IOException(MESSAGE));
56                 
57                 try {
58                         ExceptionUtils.tryClose(cm);
59                 }
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());
66                 }
67         }
68         
69         // Try closing a null pointer. 
70         // This should be harmless (no exception thrown).
71         @Test
72         public void test_tryClose_null() throws QDException 
73         {
74                 ExceptionUtils.tryClose(null);
75         }
76
77 }