• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito;
6 
7 import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
8 
9 import java.util.Collection;
10 
11 import org.mockito.internal.stubbing.answers.AnswersWithDelay;
12 import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
13 import org.mockito.internal.stubbing.answers.ReturnsElementsOf;
14 import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
15 import org.mockito.stubbing.Answer;
16 import org.mockito.stubbing.Answer1;
17 import org.mockito.stubbing.Answer2;
18 import org.mockito.stubbing.Answer3;
19 import org.mockito.stubbing.Answer4;
20 import org.mockito.stubbing.Answer5;
21 import org.mockito.stubbing.Answer6;
22 import org.mockito.stubbing.VoidAnswer1;
23 import org.mockito.stubbing.VoidAnswer2;
24 import org.mockito.stubbing.VoidAnswer3;
25 import org.mockito.stubbing.VoidAnswer4;
26 import org.mockito.stubbing.VoidAnswer5;
27 import org.mockito.stubbing.VoidAnswer6;
28 
29 /**
30  * Additional answers provides factory methods for answers.
31  *
32  * <p>Currently offer answers that can return the parameter of an invocation at a certain position,
33  * along with answers that draw on a strongly typed interface to provide a neater way to write custom answers
34  * that either return a value or are void (see answer interfaces in org.mockito.stubbing).
35  *
36  * <p>See factory methods for more information : {@link #returnsFirstArg}, {@link #returnsSecondArg},
37  * {@link #returnsLastArg}, {@link #returnsArgAt}, {@link #answer} and {@link #answerVoid}
38  *
39  * @since 1.9.5
40  */
41 @SuppressWarnings("unchecked")
42 public final class AdditionalAnswers {
43     /**
44      * Returns the first parameter of an invocation.
45      *
46      * <p>
47      *     This additional answer could be used at stub time using the
48      *     <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
49      *
50      * <pre class="code"><code class="java">
51      * given(carKeyFob.authenticate(carKey)).will(returnsFirstArg());
52      * doAnswer(returnsFirstArg()).when(carKeyFob).authenticate(carKey);
53      * </code></pre>
54      * </p>
55      *
56      * <p>
57      * This methods works with varargs as well, mockito will expand the vararg to return the argument
58      * at the given position. Suppose the following signature :
59      *
60      * <pre class="code"><code class="java">
61      * interface Person {
62      *     Dream remember(Dream... dreams);
63      * }
64      *
65      * // returns dream1
66      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsFirstArg());
67      * </code></pre>
68      *
69      * Mockito will return the vararg array if the first argument is a vararg in the method
70      * and if the return type has the same type as the vararg array.
71      *
72      * <pre class="code"><code class="java">
73      * interface Person {
74      *     Dream[] remember(Dream... otherDreams);
75      * }
76      *
77      * // returns otherDreams (happens to be a 4 elements array)
78      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsFirstArg());
79      * </code></pre>
80      * </p>
81      *
82      * @param <T> Return type of the invocation.
83      * @return Answer that will return the first argument of the invocation.
84      *
85      * @since 1.9.5
86      */
returnsFirstArg()87     public static <T> Answer<T> returnsFirstArg() {
88         return (Answer<T>) new ReturnsArgumentAt(0);
89     }
90 
91     /**
92      * Returns the second parameter of an invocation.
93      *
94      * <p>
95      *     This additional answer could be used at stub time using the
96      *     <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
97      *
98      * <pre class="code"><code class="java">
99      * given(trader.apply(leesFormula, onCreditDefaultSwap)).will(returnsSecondArg());
100      * doAnswer(returnsSecondArg()).when(trader).apply(leesFormula, onCreditDefaultSwap);
101      * </code></pre>
102      * </p>
103      *
104      * <p>
105      * This methods works with varargs as well, mockito will expand the vararg to return the argument
106      * at the given position. Suppose the following signature :
107      *
108      * <pre class="code"><code class="java">
109      * interface Person {
110      *     Dream remember(Dream dream, Dream... otherDreams);
111      * }
112      *
113      * // returns dream2
114      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsSecondArg());
115      * </code></pre>
116      *
117      * Mockito will return the vararg array if the second argument is a vararg in the method
118      * and if the return type has the same type as the vararg array.
119      *
120      * <pre class="code"><code class="java">
121      * interface Person {
122      *     Dream[] remember(Dream dream1, Dream... otherDreams);
123      * }
124      *
125      * // returns otherDreams (happens to be a 3 elements array)
126      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsSecondArg());
127      * </code></pre>
128      * </p>
129      *
130      * @param <T> Return type of the invocation.
131      * @return Answer that will return the second argument of the invocation.
132      *
133      * @since 1.9.5
134      */
returnsSecondArg()135     public static <T> Answer<T> returnsSecondArg() {
136         return (Answer<T>) new ReturnsArgumentAt(1);
137     }
138 
139     /**
140      * Returns the last parameter of an invocation.
141      *
142      * <p>
143      *     This additional answer could be used at stub time using the
144      *     <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
145      *
146      * <pre class="code"><code class="java">
147      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
148      * doAnswer(returnsLastArg()).when(person).remember(dream1, dream2, dream3, dream4);
149      * </code></pre>
150      * </p>
151      *
152      * <p>
153      * This methods works with varargs as well, mockito will expand the vararg to return the argument
154      * at the given position. Suppose the following signature :
155      *
156      * <pre class="code"><code class="java">
157      * interface Person {
158      *     Dream remember(Dream dream, Dream... otherDreams);
159      * }
160      *
161      * // returns dream4
162      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
163      * </code></pre>
164      *
165      * Mockito will return the vararg array if the given {@code position} targets the vararg index in the method
166      * and if the return type has the same type as the vararg array.
167      *
168      * <pre class="code"><code class="java">
169      * interface Person {
170      *     Dream[] remember(Dream dream1, Dream dream2, Dream dream3, Dream... otherDreams);
171      * }
172      *
173      * // returns otherDreams (happens to be a single element array)
174      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
175      * </code></pre>
176      * </p>
177      *
178      * @param <T> Return type of the invocation.
179      * @return Answer that will return the last argument of the invocation.
180      *
181      * @since 1.9.5
182      */
returnsLastArg()183     public static <T> Answer<T> returnsLastArg() {
184         return (Answer<T>) new ReturnsArgumentAt(ReturnsArgumentAt.LAST_ARGUMENT);
185     }
186 
187     /**
188      * Returns the parameter of an invocation at the given position.
189      *
190      * <p>
191      * This additional answer could be used at stub time using the
192      * <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
193      *
194      * <pre class="code"><code class="java">
195      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(3));
196      * doAnswer(returnsArgAt(3)).when(person).remember(dream1, dream2, dream3, dream4);
197      * </code></pre>
198      * </p>
199      *
200      * <p>
201      * This methods works with varargs as well, mockito will expand the vararg to return the argument
202      * at the given position. Suppose the following signature :
203      *
204      * <pre class="code"><code class="java">
205      * interface Person {
206      *     Dream remember(Dream dream, Dream... otherDreams);
207      * }
208      *
209      * // returns dream 3
210      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(2));
211      * </code></pre>
212      *
213      * Mockito will return the vararg array if the given {@code position} targets the vararg index in the method
214      * and if the return type has the same type as the vararg array.
215      *
216      * <pre class="code"><code class="java">
217      * interface Person {
218      *     Dream[] remember(Dream dream, Dream... otherDreams);
219      * }
220      *
221      * // returns otherDreams array (contains dream2, dream,3, dream4)
222      * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(1));
223      * </code></pre>
224      * </p>
225      *
226      * @param <T> Return type of the invocation.
227      * @param position index of the argument from the list of arguments.
228      * @return Answer that will return the argument from the given position in the argument's list
229      *
230      * @since 1.9.5
231      */
returnsArgAt(int position)232     public static <T> Answer<T> returnsArgAt(int position) {
233         return (Answer<T>) new ReturnsArgumentAt(position);
234     }
235 
236     /**
237      * An answer that directly forwards the calls to the delegate. The delegate may or may not be of the same type as the mock.
238      * If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
239      * <p>
240      * Useful for spies or partial mocks of objects that are difficult to mock
241      * or spy using the usual spy API. Possible use cases:
242      * <ul>
243      *     <li>Final classes but with an interface</li>
244      *     <li>Already custom proxied object</li>
245      *     <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
246      * </ul>
247      *
248      * <p>
249      * The difference with the regular spy:
250      * <ul>
251      *   <li>
252      *     The regular spy ({@link Mockito#spy(Object)}) contains <strong>all</strong> state from the spied instance
253      *     and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
254      *     If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
255      *     for verifications, and they can be effectively stubbed.
256      *   </li>
257      *   <li>
258      *     The mock that delegates simply delegates all methods to the delegate.
259      *     The delegate is used all the time as methods are delegated onto it.
260      *     If you call a method on a mock that delegates and it internally calls other methods on this mock,
261      *     those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
262      *     Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
263      *   </li>
264      * </ul>
265      * An example with a final class that we want to delegate to:
266      * <p>
267      * <pre class="code"><code class="java">
268      *   final class DontYouDareToMockMe implements list { ... }
269      *
270      *   DontYouDareToMockMe awesomeList = new DontYouDareToMockMe();
271      *
272      *   List mock = mock(List.class, delegatesTo(awesomeList));
273      * </code></pre>
274      *
275      * <p>
276      * This feature suffers from the same drawback as the spy.
277      * The mock will call the delegate if you use regular when().then() stubbing style.
278      * Since the real implementation is called this might have some side effects.
279      * Therefore you should use the doReturn|Throw|Answer|CallRealMethod stubbing style. Example:
280      *
281      * <pre class="code"><code class="java">
282      *   List listWithDelegate = mock(List.class, AdditionalAnswers.delegatesTo(awesomeList));
283      *
284      *   //Impossible: real method is called so listWithDelegate.get(0) throws IndexOutOfBoundsException (the list is yet empty)
285      *   when(listWithDelegate.get(0)).thenReturn("foo");
286      *
287      *   //You have to use doReturn() for stubbing
288      *   doReturn("foo").when(listWithDelegate).get(0);
289      * </code></pre>
290      *
291      * @param delegate The delegate to forward calls to. It does not have to be of the same type as the mock (although it usually is).
292      *                 The only requirement is that the instance should have compatible method signatures including the return values.
293      *                 Only the methods that were actually executed on the mock need to be present on the delegate type.
294      * @return the answer
295      *
296      * @since 1.9.5
297      */
delegatesTo(Object delegate)298     public static <T> Answer<T> delegatesTo(Object delegate) {
299         return (Answer<T>) new ForwardsInvocations(delegate);
300     }
301 
302     /**
303      * Returns elements of the collection. Keeps returning the last element forever.
304      * Might be useful on occasion when you have a collection of elements to return.
305      * <p>
306      * <pre class="code"><code class="java">
307      *   //this:
308      *   when(mock.foo()).thenReturn(1, 2, 3);
309      *
310      *   //is equivalent to:
311      *   when(mock.foo()).thenAnswer(AdditionalAnswers.returnsElementsOf(Arrays.asList(1, 2, 3)));
312      * </code></pre>
313      *
314      * @param elements The collection of elements to return.
315      * @return the answer
316      *
317      * @since 1.9.5
318      */
returnsElementsOf(Collection<?> elements)319     public static <T> Answer<T> returnsElementsOf(Collection<?> elements) {
320         return (Answer<T>) new ReturnsElementsOf(elements);
321     }
322 
323     /**
324      * Returns an answer after a delay with a defined length.
325      *
326      * @param <T> return type
327      * @param sleepyTime the delay in milliseconds
328      * @param answer interface to the answer which provides the intended return value.
329      * @return the answer object to use
330      *
331      * @since 2.8.44
332      */
answersWithDelay(long sleepyTime, Answer<T> answer)333     public static <T> Answer<T> answersWithDelay(long sleepyTime, Answer<T> answer) {
334         return (Answer<T>) new AnswersWithDelay(sleepyTime, (Answer<Object>) answer);
335     }
336 
337     /**
338      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
339      * ideally in Java 8
340      * @param answer interface to the answer - which is expected to return something
341      * @param <T> return type
342      * @param <A> input parameter type 1
343      * @return the answer object to use
344      * @since 2.1.0
345      */
answer(Answer1<T, A> answer)346     public static <T, A> Answer<T> answer(Answer1<T, A> answer) {
347         return toAnswer(answer);
348     }
349 
350     /**
351      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
352      * ideally in Java 8
353      * @param answer interface to the answer - a void method
354      * @param <A> input parameter type 1
355      * @return the answer object to use
356      * @since 2.1.0
357      */
answerVoid(VoidAnswer1<A> answer)358     public static <A> Answer<Void> answerVoid(VoidAnswer1<A> answer) {
359         return toAnswer(answer);
360     }
361 
362     /**
363      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
364      * ideally in Java 8
365      * @param answer interface to the answer - which is expected to return something
366      * @param <T> return type
367      * @param <A> input parameter type 1
368      * @param <B> input parameter type 2
369      * @return the answer object to use
370      * @since 2.1.0
371      */
answer(Answer2<T, A, B> answer)372     public static <T, A, B> Answer<T> answer(Answer2<T, A, B> answer) {
373         return toAnswer(answer);
374     }
375 
376     /**
377      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
378      * ideally in Java 8
379      * @param answer interface to the answer - a void method
380      * @param <A> input parameter type 1
381      * @param <B> input parameter type 2
382      * @return the answer object to use
383      * @since 2.1.0
384      */
answerVoid(VoidAnswer2<A, B> answer)385     public static <A, B> Answer<Void> answerVoid(VoidAnswer2<A, B> answer) {
386         return toAnswer(answer);
387     }
388 
389     /**
390      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
391      * ideally in Java 8
392      * @param answer interface to the answer - which is expected to return something
393      * @param <T> return type
394      * @param <A> input parameter type 1
395      * @param <B> input parameter type 2
396      * @param <C> input parameter type 3
397      * @return the answer object to use
398      * @since 2.1.0
399      */
answer(Answer3<T, A, B, C> answer)400     public static <T, A, B, C> Answer<T> answer(Answer3<T, A, B, C> answer) {
401         return toAnswer(answer);
402     }
403 
404     /**
405      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
406      * ideally in Java 8
407      * @param answer interface to the answer - a void method
408      * @param <A> input parameter type 1
409      * @param <B> input parameter type 2
410      * @param <C> input parameter type 3
411      * @return the answer object to use
412      * @since 2.1.0
413      */
answerVoid(VoidAnswer3<A, B, C> answer)414     public static <A, B, C> Answer<Void> answerVoid(VoidAnswer3<A, B, C> answer) {
415         return toAnswer(answer);
416     }
417 
418     /**
419      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
420      * ideally in Java 8
421      * @param answer interface to the answer - which is expected to return something
422      * @param <T> return type
423      * @param <A> input parameter type 1
424      * @param <B> input parameter type 2
425      * @param <C> input parameter type 3
426      * @param <D> input parameter type 4
427      * @return the answer object to use
428      * @since 2.1.0
429      */
answer(Answer4<T, A, B, C, D> answer)430     public static <T, A, B, C, D> Answer<T> answer(Answer4<T, A, B, C, D> answer) {
431         return toAnswer(answer);
432     }
433 
434     /**
435      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
436      * ideally in Java 8
437      * @param answer interface to the answer - a void method
438      * @param <A> input parameter type 1
439      * @param <B> input parameter type 2
440      * @param <C> input parameter type 3
441      * @param <D> input parameter type 4
442      * @return the answer object to use
443      * @since 2.1.0
444      */
answerVoid(VoidAnswer4<A, B, C, D> answer)445     public static <A, B, C, D> Answer<Void> answerVoid(VoidAnswer4<A, B, C, D> answer) {
446         return toAnswer(answer);
447     }
448 
449     /**
450      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
451      * ideally in Java 8
452      * @param answer interface to the answer - which is expected to return something
453      * @param <T> return type
454      * @param <A> input parameter type 1
455      * @param <B> input parameter type 2
456      * @param <C> input parameter type 3
457      * @param <D> input parameter type 4
458      * @param <E> input parameter type 5
459      * @return the answer object to use
460      * @since 2.1.0
461      */
answer(Answer5<T, A, B, C, D, E> answer)462     public static <T, A, B, C, D, E> Answer<T> answer(Answer5<T, A, B, C, D, E> answer) {
463         return toAnswer(answer);
464     }
465 
466     /**
467      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
468      * ideally in Java 8
469      *
470      * @param answer interface to the answer - a void method
471      * @param <A> input parameter type 1
472      * @param <B> input parameter type 2
473      * @param <C> input parameter type 3
474      * @param <D> input parameter type 4
475      * @param <E> input parameter type 5
476      * @return the answer object to use
477      * @since 2.1.0
478      */
answerVoid(VoidAnswer5<A, B, C, D, E> answer)479     public static <A, B, C, D, E> Answer<Void> answerVoid(VoidAnswer5<A, B, C, D, E> answer) {
480         return toAnswer(answer);
481     }
482 
483     /**
484      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
485      * idiomatically in Java 8
486      *
487      * @param answer interface to the answer - which is expected to return something
488      * @param <T> return type
489      * @param <A> input parameter type 1
490      * @param <B> input parameter type 2
491      * @param <C> input parameter type 3
492      * @param <D> input parameter type 4
493      * @param <E> input parameter type 5
494      * @param <F> input parameter type 6
495      * @return the answer object to use
496      * @since 2.26.0
497      */
answer(Answer6<T, A, B, C, D, E, F> answer)498     public static <T, A, B, C, D, E, F> Answer<T> answer(Answer6<T, A, B, C, D, E, F> answer) {
499         return toAnswer(answer);
500     }
501 
502     /**
503      * Creates an answer from a functional interface - allows for a strongly typed answer to be created
504      * idiomatically in Java 8
505      *
506      * @param answer interface to the answer - a void method
507      * @param <A> input parameter type 1
508      * @param <B> input parameter type 2
509      * @param <C> input parameter type 3
510      * @param <D> input parameter type 4
511      * @param <E> input parameter type 5
512      * @param <F> input parameter type 6
513      * @return the answer object to use
514      * @since 2.26.0
515      */
answerVoid(VoidAnswer6<A, B, C, D, E, F> answer)516     public static <A, B, C, D, E, F> Answer<Void> answerVoid(VoidAnswer6<A, B, C, D, E, F> answer) {
517         return toAnswer(answer);
518     }
519 
AdditionalAnswers()520     private AdditionalAnswers() {}
521 }
522