View Javadoc
1   /*
2    * MIT License
3    * Copyright (c) 2006-2025 JMockit developers
4    * See LICENSE file for full license text.
5    */
6   package mockit;
7   
8   import static org.junit.jupiter.api.Assertions.assertEquals;
9   import static org.junit.jupiter.api.Assertions.assertFalse;
10  import static org.junit.jupiter.api.Assertions.assertNotNull;
11  
12  import java.text.DateFormat;
13  import java.text.SimpleDateFormat;
14  import java.util.Date;
15  
16  import mockit.integration.junit5.JMockitExtension;
17  
18  import org.junit.jupiter.api.Test;
19  import org.junit.jupiter.api.extension.ExtendWith;
20  
21  /**
22   * The Class MockingNewInstancesWithVaryingBehaviorTest.
23   */
24  @ExtendWith(JMockitExtension.class)
25  class MockingNewInstancesWithVaryingBehaviorTest {
26  
27      /** The Constant DATE_FORMAT. */
28      static final String DATE_FORMAT = "yyyy-MM-dd";
29  
30      /** The Constant FORMATTED_DATE. */
31      static final String FORMATTED_DATE = "2012-02-28";
32  
33      /** The Constant TIME_FORMAT. */
34      static final String TIME_FORMAT = "HH";
35  
36      /** The Constant FORMATTED_TIME. */
37      static final String FORMATTED_TIME = "13";
38  
39      /**
40       * Exercise and verify tested code.
41       */
42      void exerciseAndVerifyTestedCode() {
43          Date now = new Date();
44  
45          String hour = new SimpleDateFormat(TIME_FORMAT).format(now);
46          assertEquals(FORMATTED_TIME, hour);
47  
48          String date = new SimpleDateFormat(DATE_FORMAT).format(now);
49          assertEquals(FORMATTED_DATE, date);
50      }
51  
52      /// Tests using the Faking API
53      /// /////////////////////////////////////////////////////////////////////////////////////////////////////////
54  
55      /** The date format. */
56      DateFormat dateFormat;
57  
58      /** The hour format. */
59      DateFormat hourFormat;
60  
61      /**
62       * Using fakes with invocation parameter.
63       */
64      @Test
65      void usingFakesWithInvocationParameter() {
66          new MockUp<SimpleDateFormat>() {
67              @Mock
68              void $init(Invocation inv, String pattern) {
69                  DateFormat dt = inv.getInvokedInstance();
70                  if (DATE_FORMAT.equals(pattern)) {
71                      dateFormat = dt;
72                  } else if (TIME_FORMAT.equals(pattern)) {
73                      hourFormat = dt;
74                  }
75              }
76          };
77  
78          new MockUp<DateFormat>() {
79              @Mock
80              String format(Invocation inv, Date d) {
81                  assertNotNull(d);
82                  DateFormat dt = inv.getInvokedInstance();
83                  if (dt == dateFormat) {
84                      return FORMATTED_DATE;
85                  }
86                  if (dt == hourFormat) {
87                      return FORMATTED_TIME;
88                  } else {
89                      return null;
90                  }
91              }
92          };
93  
94          exerciseAndVerifyTestedCode();
95      }
96  
97      /// Tests using the Mocking API
98      /// ////////////////////////////////////////////////////////////////////////////////////////////////////////
99  
100     /**
101      * Using instantiation recording.
102      *
103      * @param anyDateFormat
104      *            the any date format
105      */
106     @Test
107     void usingInstantiationRecording(@Mocked SimpleDateFormat anyDateFormat) {
108         new Expectations() {
109             {
110                 SimpleDateFormat dateFmt = new SimpleDateFormat(DATE_FORMAT);
111                 dateFmt.format((Date) any);
112                 result = FORMATTED_DATE;
113 
114                 SimpleDateFormat hourFmt = new SimpleDateFormat(TIME_FORMAT);
115                 hourFmt.format((Date) any);
116                 result = FORMATTED_TIME;
117             }
118         };
119 
120         exerciseAndVerifyTestedCode();
121     }
122 
123     /**
124      * The Class Collaborator.
125      */
126     static class Collaborator {
127 
128         /** The value. */
129         final int value;
130 
131         /**
132          * Instantiates a new collaborator.
133          */
134         Collaborator() {
135             value = -1;
136         }
137 
138         /**
139          * Instantiates a new collaborator.
140          *
141          * @param value
142          *            the value
143          */
144         Collaborator(int value) {
145             this.value = value;
146         }
147 
148         /**
149          * Gets the value.
150          *
151          * @return the value
152          */
153         int getValue() {
154             return value;
155         }
156 
157         /**
158          * Checks if is positive.
159          *
160          * @return true, if is positive
161          */
162         boolean isPositive() {
163             return value > 0;
164         }
165     }
166 
167     /** The col. */
168     Collaborator col;
169 
170     /** The col 5. */
171     Collaborator col5;
172 
173     /** The col 6. */
174     Collaborator col6;
175 
176     /**
177      * Match method calls on instances created with specific constructor calls.
178      *
179      * @param anyCol
180      *            the any col
181      */
182     @Test
183     void matchMethodCallsOnInstancesCreatedWithSpecificConstructorCalls(@Mocked final Collaborator anyCol) {
184         new Expectations() {
185             {
186                 col5 = new Collaborator(5);
187                 col5.getValue();
188                 result = 123;
189                 times = 2;
190 
191                 col = new Collaborator();
192                 times = 1;
193                 col6 = new Collaborator(6);
194             }
195         };
196 
197         assertEquals(0, new Collaborator().getValue());
198 
199         Collaborator newCol1 = new Collaborator(5);
200         assertEquals(123, newCol1.getValue());
201 
202         Collaborator newCol2 = new Collaborator(6);
203         assertEquals(0, newCol2.getValue());
204         assertFalse(newCol2.isPositive());
205 
206         Collaborator newCol3 = new Collaborator(5);
207         assertEquals(123, newCol3.getValue());
208         assertFalse(newCol3.isPositive());
209 
210         new Verifications() {
211             {
212                 new Collaborator(anyInt);
213                 times = 3;
214                 col.getValue();
215                 times = 1;
216                 col6.getValue();
217                 times = 1;
218                 col5.isPositive();
219                 times = 1;
220                 col6.isPositive();
221                 times = 1;
222             }
223         };
224     }
225 
226     /**
227      * Record different results for instances created with different constructors.
228      *
229      * @param anyCol
230      *            the any col
231      */
232     @Test
233     void recordDifferentResultsForInstancesCreatedWithDifferentConstructors(@Mocked final Collaborator anyCol) {
234         new Expectations() {
235             {
236                 anyCol.getValue();
237                 result = 1;
238 
239                 Collaborator col2 = new Collaborator(anyInt);
240                 col2.getValue();
241                 result = 2;
242             }
243         };
244 
245         int valueFromRecordedConstructor = new Collaborator(10).getValue();
246         int valueFromAnyOtherConstructor = new Collaborator().getValue();
247 
248         assertEquals(2, valueFromRecordedConstructor);
249         assertEquals(1, valueFromAnyOtherConstructor);
250     }
251 }