View Javadoc
1   package mockit;
2   
3   import static org.junit.jupiter.api.Assertions.assertEquals;
4   import static org.junit.jupiter.api.Assertions.assertFalse;
5   import static org.junit.jupiter.api.Assertions.assertNotSame;
6   import static org.junit.jupiter.api.Assertions.assertNull;
7   import static org.junit.jupiter.api.Assertions.assertSame;
8   import static org.junit.jupiter.api.Assertions.assertTrue;
9   import static org.junit.jupiter.api.Assertions.fail;
10  
11  import java.io.DataInputStream;
12  import java.io.File;
13  import java.io.FileInputStream;
14  import java.io.FileOutputStream;
15  import java.io.FileWriter;
16  import java.io.PrintWriter;
17  import java.io.Writer;
18  import java.nio.file.Path;
19  import java.time.Duration;
20  import java.util.Calendar;
21  import java.util.Date;
22  import java.util.GregorianCalendar;
23  import java.util.TimeZone;
24  import java.util.jar.Attributes;
25  import java.util.jar.JarEntry;
26  import java.util.jar.JarFile;
27  import java.util.jar.Manifest;
28  import java.util.logging.LogManager;
29  import java.util.logging.Logger;
30  
31  import org.junit.Test;
32  
33  /**
34   * The Class JREMockingTest.
35   */
36  public final class JREMockingTest {
37      // Mocking java.io.File
38      // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
39  
40      /**
41       * Mocking of file.
42       *
43       * @param file
44       *            the file
45       */
46      @Test
47      public void mockingOfFile(@Mocked final File file) {
48          new Expectations() {
49              {
50                  file.exists();
51                  result = true;
52              }
53          };
54  
55          File f = Path.of("...").toFile();
56          assertTrue(f.exists());
57      }
58  
59      /**
60       * Mocking file and recording expectation to match on specific constructor call.
61       *
62       * @param anyFile
63       *            the any file
64       */
65      @Test
66      public void mockingFileAndRecordingExpectationToMatchOnSpecificConstructorCall(@Mocked File anyFile) {
67          new Expectations() {
68              {
69                  Path.of("a.txt").toFile().exists();
70                  result = true;
71              }
72          };
73  
74          boolean aExists = Path.of("a.txt").toFile().exists();
75          // noinspection TooBroadScope
76          boolean bExists = Path.of("b.txt").toFile().exists();
77  
78          assertTrue(aExists);
79          assertFalse(bExists);
80      }
81  
82      // Faking java.util.Calendar
83      // ///////////////////////////////////////////////////////////////////////////////////////////////////////////
84  
85      /**
86       * Faking of calendar.
87       */
88      @Test
89      public void fakingOfCalendar() {
90          final Calendar calCST = new GregorianCalendar(2010, Calendar.MAY, 15);
91          final TimeZone tzCST = TimeZone.getTimeZone("CST");
92          new MockUp<Calendar>() {
93              @Mock
94              Calendar getInstance(Invocation inv, TimeZone tz) {
95                  return tz == tzCST ? calCST : inv.<Calendar> proceed();
96              }
97          };
98  
99          Calendar cal1 = Calendar.getInstance(tzCST);
100         assertSame(calCST, cal1);
101         assertEquals(2010, cal1.get(Calendar.YEAR));
102 
103         TimeZone tzPST = TimeZone.getTimeZone("PST");
104         Calendar cal2 = Calendar.getInstance(tzPST);
105         assertNotSame(calCST, cal2);
106     }
107 
108     // Mocking java.util.Date
109     // //////////////////////////////////////////////////////////////////////////////////////////////////////////////
110 
111     /**
112      * Regular mocking of annotated JRE method.
113      *
114      * @param d
115      *            the d
116      *
117      * @throws Exception
118      *             the exception
119      */
120     @Test
121     public void regularMockingOfAnnotatedJREMethod(@Mocked Date d) throws Exception {
122         assertTrue(d.getClass().getDeclaredMethod("parse", String.class).isAnnotationPresent(Deprecated.class));
123     }
124 
125     /**
126      * Dynamic mocking of annotated JRE method.
127      *
128      * @throws Exception
129      *             the exception
130      */
131     @Test
132     @SuppressWarnings("deprecation")
133     public void dynamicMockingOfAnnotatedJREMethod() throws Exception {
134         final Date d = new Date();
135 
136         new Expectations(d) {
137             {
138                 d.getMinutes();
139                 result = 5;
140             }
141         };
142 
143         assertEquals(5, d.getMinutes());
144         assertTrue(Date.class.getDeclaredMethod("getMinutes").isAnnotationPresent(Deprecated.class));
145     }
146 
147     // Mocking of IO classes
148     // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
149 
150     /** The stream. */
151     @Injectable
152     FileOutputStream stream;
153 
154     /** The writer. */
155     @Injectable
156     Writer writer;
157 
158     /**
159      * Dynamic mocking of file output stream through mock field.
160      *
161      * @throws Exception
162      *             the exception
163      */
164     @Test
165     public void dynamicMockingOfFileOutputStreamThroughMockField() throws Exception {
166         new Expectations() {
167             {
168                 // noinspection ConstantConditions
169                 stream.write((byte[]) any);
170             }
171         };
172 
173         stream.write("Hello world".getBytes());
174         writer.append('x');
175 
176         new Verifications() {
177             {
178                 writer.append('x');
179             }
180         };
181     }
182 
183     // Un-mockable JRE classes
184     // /////////////////////////////////////////////////////////////////////////////////////////////////////////////
185 
186     /**
187      * Attempt to mock unmockable JRE class.
188      *
189      * @param unmockable
190      *            the unmockable
191      */
192     @Test(expected = IllegalArgumentException.class)
193     public void attemptToMockUnmockableJREClass(@Mocked FileInputStream unmockable) {
194         fail("Should never get here");
195     }
196 
197     /**
198      * Attempt to mock unmockable JRE class.
199      *
200      * @param unmockable
201      *            the unmockable
202      */
203     @Test(expected = IllegalArgumentException.class)
204     public void attemptToMockUnmockableJREClass(@Mocked FileOutputStream unmockable) {
205         fail("Should never get here");
206     }
207 
208     /**
209      * Attempt to mock unmockable JRE class.
210      *
211      * @param unmockable
212      *            the unmockable
213      */
214     @Test(expected = IllegalArgumentException.class)
215     public void attemptToMockUnmockableJREClass(@Mocked Writer unmockable) {
216         fail("Should never get here");
217     }
218 
219     /**
220      * Attempt to mock unmockable JRE class.
221      *
222      * @param unmockable
223      *            the unmockable
224      */
225     @Test(expected = IllegalArgumentException.class)
226     public void attemptToMockUnmockableJREClass(@Mocked FileWriter unmockable) {
227         fail("Should never get here");
228     }
229 
230     /**
231      * Attempt to mock unmockable JRE class.
232      *
233      * @param unmockable
234      *            the unmockable
235      */
236     @Test(expected = IllegalArgumentException.class)
237     public void attemptToMockUnmockableJREClass(@Mocked PrintWriter unmockable) {
238         fail("Should never get here");
239     }
240 
241     /**
242      * Attempt to mock unmockable JRE class.
243      *
244      * @param unmockable
245      *            the unmockable
246      */
247     @Test(expected = IllegalArgumentException.class)
248     public void attemptToMockUnmockableJREClass(@Mocked DataInputStream unmockable) {
249         fail("Should never get here");
250     }
251 
252     /**
253      * Attempt to mock unmockable JRE class.
254      *
255      * @param unmockable
256      *            the unmockable
257      */
258     @Test(expected = IllegalArgumentException.class)
259     public void attemptToMockUnmockableJREClass(@Mocked StringBuffer unmockable) {
260         fail("Should never get here");
261     }
262 
263     /**
264      * Attempt to mock unmockable JRE class.
265      *
266      * @param unmockable
267      *            the unmockable
268      */
269     @Test(expected = IllegalArgumentException.class)
270     public void attemptToMockUnmockableJREClass(@Mocked StringBuilder unmockable) {
271         fail("Should never get here");
272     }
273 
274     /**
275      * Attempt to mock unmockable JRE class.
276      *
277      * @param unmockable
278      *            the unmockable
279      */
280     @Test(expected = IllegalArgumentException.class)
281     public void attemptToMockUnmockableJREClass(@Mocked Exception unmockable) {
282         fail("Should never get here");
283     }
284 
285     /**
286      * Attempt to mock unmockable JRE class.
287      *
288      * @param unmockable
289      *            the unmockable
290      */
291     @Test(expected = IllegalArgumentException.class)
292     public void attemptToMockUnmockableJREClass(@Mocked Throwable unmockable) {
293         fail("Should never get here");
294     }
295 
296     /**
297      * Attempt to mock unmockable JRE class.
298      *
299      * @param unmockable
300      *            the unmockable
301      */
302     @Test(expected = IllegalArgumentException.class)
303     public void attemptToMockUnmockableJREClass(@Mocked Thread unmockable) {
304         fail("Should never get here");
305     }
306 
307     /**
308      * Attempt to mock unmockable JRE class.
309      *
310      * @param unmockable
311      *            the unmockable
312      */
313     @Test(expected = IllegalArgumentException.class)
314     public void attemptToMockUnmockableJREClass(@Mocked ThreadLocal<?> unmockable) {
315         fail("Should never get here");
316     }
317 
318     /**
319      * Attempt to mock unmockable JRE class.
320      *
321      * @param unmockable
322      *            the unmockable
323      */
324     @Test(expected = IllegalArgumentException.class)
325     public void attemptToMockUnmockableJREClass(@Mocked ClassLoader unmockable) {
326         fail("Should never get here");
327     }
328 
329     /**
330      * Attempt to mock unmockable JRE class.
331      *
332      * @param unmockable
333      *            the unmockable
334      */
335     @Test(expected = IllegalArgumentException.class)
336     public void attemptToMockUnmockableJREClass(@Mocked Class<?> unmockable) {
337         fail("Should never get here");
338     }
339 
340     /**
341      * Attempt to mock unmockable JRE class.
342      *
343      * @param unmockable
344      *            the unmockable
345      */
346     @Test(expected = IllegalArgumentException.class)
347     public void attemptToMockUnmockableJREClass(@Mocked Math unmockable) {
348         fail("Should never get here");
349     }
350 
351     /**
352      * Attempt to mock unmockable JRE class.
353      *
354      * @param unmockable
355      *            the unmockable
356      */
357     @Test(expected = IllegalArgumentException.class)
358     public void attemptToMockUnmockableJREClass(@Mocked StrictMath unmockable) {
359         fail("Should never get here");
360     }
361 
362     /**
363      * Attempt to mock unmockable JRE class.
364      *
365      * @param unmockable
366      *            the unmockable
367      */
368     @Test(expected = IllegalArgumentException.class)
369     public void attemptToMockUnmockableJREClass(@Mocked Object unmockable) {
370         fail("Should never get here");
371     }
372 
373     /**
374      * Attempt to mock unmockable JRE class.
375      *
376      * @param unmockable
377      *            the unmockable
378      */
379     @Test(expected = IllegalArgumentException.class)
380     public void attemptToMockUnmockableJREClass(@Mocked Enum<?> unmockable) {
381         fail("Should never get here");
382     }
383 
384     /**
385      * Attempt to mock unmockable JRE class.
386      *
387      * @param unmockable
388      *            the unmockable
389      */
390     @Test(expected = IllegalArgumentException.class)
391     public void attemptToMockUnmockableJREClass(@Mocked System unmockable) {
392         fail("Should never get here");
393     }
394 
395     /**
396      * Attempt to mock unmockable JRE class.
397      *
398      * @param unmockable
399      *            the unmockable
400      */
401     @Test(expected = IllegalArgumentException.class)
402     public void attemptToMockUnmockableJREClass(@Mocked JarFile unmockable) {
403         fail("Should never get here");
404     }
405 
406     /**
407      * Attempt to mock unmockable JRE class.
408      *
409      * @param unmockable
410      *            the unmockable
411      */
412     @Test(expected = IllegalArgumentException.class)
413     public void attemptToMockUnmockableJREClass(@Mocked JarEntry unmockable) {
414         fail("Should never get here");
415     }
416 
417     /**
418      * Attempt to mock unmockable JRE class.
419      *
420      * @param unmockable
421      *            the unmockable
422      */
423     @Test(expected = IllegalArgumentException.class)
424     public void attemptToMockUnmockableJREClass(@Mocked Manifest unmockable) {
425         fail("Should never get here");
426     }
427 
428     /**
429      * Attempt to mock unmockable JRE class.
430      *
431      * @param unmockable
432      *            the unmockable
433      */
434     @Test(expected = IllegalArgumentException.class)
435     public void attemptToMockUnmockableJREClass(@Mocked Attributes unmockable) {
436         fail("Should never get here");
437     }
438 
439     /**
440      * Attempt to mock unmockable JRE class.
441      *
442      * @param unmockable
443      *            the unmockable
444      */
445     @Test(expected = IllegalArgumentException.class)
446     public void attemptToMockUnmockableJREClass(@SuppressWarnings("Since15") @Mocked Duration unmockable) {
447         fail("Should never get here");
448     }
449 
450     // Mocking java.time
451     // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
452 
453     /**
454      * The Interface DurationProvider.
455      */
456     public interface DurationProvider {
457         /**
458          * Gets the duration.
459          *
460          * @return the duration
461          */
462         @SuppressWarnings("Since15")
463         Duration getDuration();
464     }
465 
466     /**
467      * Mock method which returns A duration.
468      *
469      * @param mock
470      *            the mock
471      */
472     @Test
473     public void mockMethodWhichReturnsADuration(@Mocked DurationProvider mock) {
474         Object d = mock.getDuration();
475 
476         assertNull(d);
477     }
478 
479     // Mocking java.util.logging
480     // ///////////////////////////////////////////////////////////////////////////////////////////////////////////
481 
482     /**
483      * Mock log manager.
484      *
485      * @param mock
486      *            the mock
487      */
488     @Test
489     public void mockLogManager(@Mocked LogManager mock) {
490         LogManager logManager = LogManager.getLogManager();
491         // noinspection MisorderedAssertEqualsArguments
492         assertSame(mock, logManager);
493     }
494 
495     /**
496      * Mock logger.
497      *
498      * @param mock
499      *            the mock
500      */
501     @Test
502     public void mockLogger(@Mocked Logger mock) {
503         // TODO: this call causes Surefire to fail: assertNotNull(LogManager.getLogManager());
504         // noinspection MisorderedAssertEqualsArguments
505         assertSame(mock, Logger.getLogger("test"));
506     }
507 }