1
2
3
4
5
6
7
8
9 package com.codebox.instance;
10
11 import java.lang.reflect.Constructor;
12
13 import org.junit.jupiter.api.Assertions;
14 import org.junit.jupiter.api.Test;
15 import org.opentest4j.AssertionFailedError;
16
17
18
19
20 class ConstructorInstanceExceptionTest {
21
22
23
24
25 abstract static class AbstractClass {
26
27
28
29
30 public AbstractClass() {
31 }
32 }
33
34
35
36
37
38 static class PrivateConstructorClass {
39
40
41
42
43 private PrivateConstructorClass() {
44 }
45 }
46
47
48
49
50 static class ThrowsOnConstruct {
51
52
53
54
55 public ThrowsOnConstruct() {
56 throw new RuntimeException("fail");
57 }
58 }
59
60 static class PublicCtorClass {
61 public PublicCtorClass() {
62 }
63 }
64
65 static final class UtilityClass {
66 private UtilityClass() {
67 }
68 }
69
70
71
72
73
74
75
76 @Test
77 void testNewInstanceInstantiationException() throws Exception {
78 Constructor<?> ctor = AbstractClass.class.getDeclaredConstructor();
79 Assertions.assertThrows(org.opentest4j.AssertionFailedError.class, () -> ConstructorInstance.newInstance(ctor));
80 }
81
82
83
84
85
86
87
88 @Test
89 void testNewInstanceInvocationTargetException() throws Exception {
90 Constructor<?> ctor = ThrowsOnConstruct.class.getDeclaredConstructor();
91 Assertions.assertThrows(org.opentest4j.AssertionFailedError.class, () -> ConstructorInstance.newInstance(ctor));
92 }
93
94 @Test
95 void testNewInstanceSuccess() throws Exception {
96 Constructor<?> ctor = PublicCtorClass.class.getDeclaredConstructor();
97 Assertions.assertInstanceOf(PublicCtorClass.class, ConstructorInstance.newInstance(ctor));
98 }
99
100 @Test
101 void testNewInstanceWithInaccessibleConstructorThrowsAssertionFailure() throws Exception {
102 Constructor<?> ctor = PrivateConstructorClass.class.getDeclaredConstructor();
103 Assertions.assertThrows(AssertionFailedError.class, () -> ConstructorInstance.newInstance(ctor));
104 }
105
106 @Test
107 void testInaccessibleUtilityClass() {
108 Assertions.assertDoesNotThrow(() -> ConstructorInstance.inaccessible(UtilityClass.class));
109 }
110
111 }