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.assertNotNull;
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.ByteArrayOutputStream;
12  import java.io.File;
13  import java.io.IOException;
14  import java.io.OutputStream;
15  import java.net.HttpURLConnection;
16  import java.net.URL;
17  import java.net.URLConnection;
18  import java.net.URLStreamHandler;
19  import java.nio.file.Path;
20  
21  import org.junit.jupiter.api.Test;
22  
23  /**
24   * The Class ClassLoadingAndJREMocksTest.
25   */
26  class ClassLoadingAndJREMocksTest {
27  
28      /**
29       * The Class Foo.
30       */
31      static class Foo {
32      }
33  
34      /**
35       * Fake file.
36       */
37      @Test
38      void fakeFile() {
39          new MockUp<File>() {
40              @Mock
41              void $init(String name) {
42              } // not necessary, except to verify non-occurrence of NPE
43  
44              @Mock
45              boolean exists() {
46                  return true;
47              }
48          };
49  
50          new Foo(); // causes a class load
51          assertTrue(Path.of("filePath").toFile().exists());
52      }
53  
54      /**
55       * Fake file safely using reentrant fake method.
56       */
57      @Test
58      void fakeFileSafelyUsingReentrantFakeMethod() {
59          new MockUp<File>() {
60              @Mock
61              boolean exists(Invocation inv) {
62                  File it = inv.getInvokedInstance();
63                  return "testFile".equals(it.getName()) || inv.<Boolean> proceed();
64              }
65          };
66  
67          checkForTheExistenceOfSeveralFiles();
68      }
69  
70      /**
71       * Check for the existence of several files.
72       */
73      void checkForTheExistenceOfSeveralFiles() {
74          assertFalse(Path.of("someOtherFile").toFile().exists());
75          assertTrue(Path.of("testFile").toFile().exists());
76          assertFalse(Path.of("yet/another/file").toFile().exists());
77          assertTrue(Path.of("testFile").toFile().exists());
78      }
79  
80      /**
81       * Fake file safely using proceed.
82       */
83      @Test
84      void fakeFileSafelyUsingProceed() {
85          new MockUp<File>() {
86              @Mock
87              boolean exists(Invocation inv) {
88                  File it = inv.getInvokedInstance();
89                  return "testFile".equals(it.getName()) || inv.<Boolean> proceed();
90              }
91          };
92  
93          checkForTheExistenceOfSeveralFiles();
94      }
95  
96      /**
97       * Attempt to mock non mockable JRE class.
98       *
99       * @param mock
100      *            the mock
101      */
102     @Test
103     void attemptToMockNonMockableJREClass(@Mocked Integer mock) {
104         assertNull(mock);
105     }
106 
107     /**
108      * Mock URL and URL connection.
109      *
110      * @param mockUrl
111      *            the mock url
112      * @param mockConnection
113      *            the mock connection
114      *
115      * @throws Exception
116      *             the exception
117      */
118     @Test
119     void mockURLAndURLConnection(@Mocked URL mockUrl, @Mocked URLConnection mockConnection) throws Exception {
120         URLConnection conn = mockUrl.openConnection();
121 
122         assertSame(mockConnection, conn);
123     }
124 
125     /**
126      * Mock URL and http URL connection.
127      *
128      * @param mockUrl
129      *            the mock url
130      * @param mockConnection
131      *            the mock connection
132      *
133      * @throws Exception
134      *             the exception
135      */
136     @Test
137     void mockURLAndHttpURLConnection(@Mocked URL mockUrl, @Mocked HttpURLConnection mockConnection) throws Exception {
138         HttpURLConnection conn = (HttpURLConnection) mockUrl.openConnection();
139         assertSame(mockConnection, conn);
140     }
141 
142     /**
143      * Mock URL and http URL connection with dynamic mock.
144      *
145      * @param mockHttpConnection
146      *            the mock http connection
147      *
148      * @throws Exception
149      *             the exception
150      */
151     @Test
152     void mockURLAndHttpURLConnectionWithDynamicMock(@Mocked final HttpURLConnection mockHttpConnection)
153             throws Exception {
154         final URL url = new URL("http://nowhere");
155 
156         new Expectations(url) {
157             {
158                 url.openConnection();
159                 result = mockHttpConnection;
160                 mockHttpConnection.getOutputStream();
161                 result = new ByteArrayOutputStream();
162             }
163         };
164 
165         // Code under test:
166         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
167         conn.setDoOutput(true);
168         conn.setRequestMethod("PUT");
169         OutputStream out = conn.getOutputStream();
170 
171         assertNotNull(out);
172 
173         new Verifications() {
174             {
175                 mockHttpConnection.setDoOutput(true);
176                 mockHttpConnection.setRequestMethod("PUT");
177             }
178         };
179     }
180 
181     /**
182      * Read resource content.
183      *
184      * @return the string
185      *
186      * @throws IOException
187      *             Signals that an I/O exception has occurred.
188      */
189     String readResourceContent() throws IOException {
190         URL url = new URL("http://remoteHost/aResource");
191         URLConnection connection = url.openConnection();
192 
193         connection.setConnectTimeout(1000);
194         connection.connect();
195 
196         return connection.getContent().toString();
197     }
198 
199     /**
200      * Cascading mocked URL with injectable cascaded URL connection.
201      *
202      * @param anyUrl
203      *            the any url
204      * @param cascadedUrlConnection
205      *            the cascaded url connection
206      *
207      * @throws Exception
208      *             the exception
209      */
210     @Test
211     void cascadingMockedURLWithInjectableCascadedURLConnection(@Mocked URL anyUrl,
212             @Injectable final URLConnection cascadedUrlConnection) throws Exception {
213         String testContent = recordURLConnectionToReturnContent(cascadedUrlConnection);
214 
215         String content = readResourceContent();
216 
217         assertEquals(testContent, content);
218     }
219 
220     /**
221      * Record URL connection to return content.
222      *
223      * @param urlConnection
224      *            the url connection
225      *
226      * @return the string
227      *
228      * @throws IOException
229      *             Signals that an I/O exception has occurred.
230      */
231     String recordURLConnectionToReturnContent(final URLConnection urlConnection) throws IOException {
232         final String testContent = "testing";
233         new Expectations() {
234             {
235                 urlConnection.getContent();
236                 result = testContent;
237             }
238         };
239         return testContent;
240     }
241 
242     /**
243      * Fake URL using injectable URL connection.
244      *
245      * @param urlConnection
246      *            the url connection
247      *
248      * @throws Exception
249      *             the exception
250      */
251     @Test
252     void fakeURLUsingInjectableURLConnection(@Injectable final URLConnection urlConnection) throws Exception {
253         final String testContent = recordURLConnectionToReturnContent(urlConnection);
254         new MockUp<URL>() {
255             @Mock
256             void $init(URL context, String spec, URLStreamHandler handler) {
257             }
258 
259             @Mock
260             URLConnection openConnection() {
261                 return urlConnection;
262             }
263         };
264 
265         String content = readResourceContent();
266 
267         assertEquals(testContent, content);
268     }
269 
270     /**
271      * Attempt to mock JRE class that is never mockable.
272      *
273      * @param mockClass
274      *            the mock class
275      */
276     @org.junit.Test(expected = IllegalArgumentException.class)
277     public void attemptToMockJREClassThatIsNeverMockable(@Mocked Class<?> mockClass) {
278         fail("Should never get here");
279     }
280 
281 }