1
2
3
4
5
6 package mockit;
7
8 import static org.junit.jupiter.api.Assertions.assertEquals;
9 import static org.junit.jupiter.api.Assertions.assertTrue;
10
11 import mockit.integration.junit5.ExpectedException;
12 import mockit.integration.junit5.JMockitExtension;
13 import mockit.internal.expectations.invocation.MissingInvocation;
14
15 import org.junit.jupiter.api.Test;
16 import org.junit.jupiter.api.extension.ExtendWith;
17
18
19
20
21 @ExtendWith(JMockitExtension.class)
22 class TestedAndMockedTest {
23
24
25
26
27 public static class ClassToBeTested {
28
29
30 private final String someData;
31
32
33 String outputData;
34
35
36 AnotherClassToBeTested collaborator;
37
38
39
40
41
42
43
44 public ClassToBeTested(String someData) {
45 this.someData = someData;
46 }
47
48
49
50
51
52
53
54
55
56
57
58 public boolean doSomeOperation(int i, String s) {
59 validateInput(i, s);
60 int j = i + doSomething();
61 doSomethingElse(s);
62 return j > 0;
63 }
64
65
66
67
68
69
70
71
72
73 static void validateInput(int i, String s) {
74 if (i <= 0 || s == null) {
75 throw new IllegalArgumentException();
76 }
77 }
78
79
80
81
82
83
84 int doSomething() {
85 return -1;
86 }
87
88
89
90
91
92
93
94 void doSomethingElse(String s) {
95 outputData = "output data: " + s;
96 }
97
98
99
100
101
102
103 int doAnotherOperation() {
104 return collaborator.doSomething() - 23;
105 }
106 }
107
108
109
110
111 static final class AnotherClassToBeTested {
112
113
114
115
116
117 int doSomething() {
118 return 123;
119 }
120 }
121
122
123 @Tested
124 AnotherClassToBeTested testedAndInjected;
125
126
127 @Tested(fullyInitialized = true)
128 @Mocked
129 ClassToBeTested tested;
130
131
132 @Injectable
133 final String testData = "test data";
134
135
136
137
138 @Test
139 void exercisePublicMethodWhileHavingHelperMethodsMocked() {
140 assertEquals(testData, tested.someData);
141
142 new Expectations() {
143 {
144 tested.doSomething();
145 result = 123;
146 }
147 };
148 new Expectations() {
149 {
150 ClassToBeTested.validateInput(anyInt, anyString);
151 }
152 };
153
154 boolean result = tested.doSomeOperation(0, "testing");
155
156 assertTrue(result);
157 assertEquals("output data: testing", tested.outputData);
158
159 new Verifications() {
160 {
161 tested.doSomethingElse(anyString);
162 times = 1;
163 }
164 };
165 }
166
167
168
169
170 @Test
171 void exerciseTopLevelTestedObjectTogetherWithInjectedSecondLevelTestedObject() {
172 assertEquals(123, testedAndInjected.doSomething());
173 assertEquals(100, tested.doAnotherOperation());
174 }
175
176
177
178
179
180
181
182 @Test
183 @ExpectedException(MissingInvocation.class)
184 void mockTestedClass(@Mocked final ClassToBeTested mock) {
185 new Expectations() {
186 {
187 mock.doSomethingElse("");
188 }
189 };
190 }
191 }