1 package org.djutils.test;
2
3 import static org.junit.jupiter.api.Assertions.assertEquals;
4 import static org.junit.jupiter.api.Assertions.assertNull;
5 import static org.junit.jupiter.api.Assertions.assertTrue;
6 import static org.junit.jupiter.api.Assertions.fail;
7
8 import java.lang.reflect.Constructor;
9
10
11
12
13
14
15
16
17
18
19
20
21 public final class ExceptionTest
22 {
23
24 private ExceptionTest()
25 {
26
27 }
28
29
30
31
32
33 public static void testExceptionClass(final Class<? extends Exception> clazz)
34 {
35 try
36 {
37 Constructor<? extends Exception> constructor = clazz.getConstructor();
38 try
39 {
40 throw constructor.newInstance();
41 }
42 catch (Exception e)
43 {
44 checkRightException(e, clazz);
45 assertNull(e.getMessage());
46 }
47
48 constructor = clazz.getConstructor(String.class);
49 try
50 {
51 throw constructor.newInstance("abc");
52 }
53 catch (Exception e)
54 {
55 checkRightException(e, clazz);
56 assertEquals("abc", e.getMessage());
57 }
58
59 constructor = clazz.getConstructor(Throwable.class);
60 try
61 {
62 throw constructor.newInstance(new IllegalArgumentException());
63 }
64 catch (Exception e)
65 {
66 checkRightException(e, clazz);
67 assertTrue(e.getMessage().contains("IllegalArgumentException"));
68 assertTrue(e.getCause() instanceof IllegalArgumentException);
69 }
70
71 constructor = clazz.getConstructor(String.class, Throwable.class);
72 try
73 {
74 throw constructor.newInstance("abc", new IllegalArgumentException("def"));
75 }
76 catch (Exception e)
77 {
78 checkRightException(e, clazz);
79 assertEquals("abc", e.getMessage());
80 assertTrue(e.getCause() instanceof IllegalArgumentException);
81 assertEquals("def", e.getCause().getMessage());
82 }
83 }
84 catch (SecurityException | NoSuchMethodException ex)
85 {
86 fail("Class " + clazz + " is missing standard and accessible exception constructor.");
87 }
88 }
89
90
91
92
93
94
95 private static void checkRightException(final Exception e, final Class<? extends Exception> clazz)
96 {
97 if (!e.getClass().equals(clazz))
98 {
99 fail("Right exception not thrown. It is " + e.getClass().getSimpleName() + " instead of " + clazz.getSimpleName());
100 }
101 }
102 }