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