• 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 org.mockito.invocation.InvocationFactory;
8 import org.mockito.invocation.MockHandler;
9 import org.mockito.listeners.InvocationListener;
10 import org.mockito.listeners.VerificationStartedListener;
11 import org.mockito.mock.MockCreationSettings;
12 import org.mockito.mock.SerializableMode;
13 import org.mockito.stubbing.Answer;
14 
15 import java.io.Serializable;
16 
17 /**
18  * Allows mock creation with additional mock settings.
19  * <p/>
20  * Don't use it too often.
21  * Consider writing simple tests that use simple mocks.
22  * Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
23  * If you cannot write a test in a simple way - refactor the code under test.
24  * <p/>
25  * Examples of mock settings:
26  * <pre class="code"><code class="java">
27  *   //Creates mock with different default answer & name
28  *   Foo mock = mock(Foo.class, withSettings()
29  *                                .defaultAnswer(RETURNS_SMART_NULLS)
30  *                                .name("cool mockie")
31  *                                );
32  *
33  *   //Creates mock with different default answer, descriptive name and extra interfaces
34  *   Foo mock = mock(Foo.class, withSettings()
35  *                                .defaultAnswer(RETURNS_SMART_NULLS)
36  *                                .name("cool mockie")
37  *                                .extraInterfaces(Bar.class));
38  * </code></pre>
39  * {@link MockSettings} has been introduced for two reasons.
40  * Firstly, to make it easy to add another mock setting when the demand comes.
41  * Secondly, to enable combining together different mock settings without introducing zillions of overloaded mock() methods.
42  */
43 public interface MockSettings extends Serializable {
44 
45     /**
46      * Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases.
47      * <p>
48      * This mysterious feature should be used very occasionally.
49      * The object under test should know exactly its collaborators & dependencies.
50      * If you happen to use it often than please make sure you are really producing simple, clean & readable code.
51      * <p>
52      * Examples:
53      * <pre class="code"><code class="java">
54      *   Foo foo = mock(Foo.class, withSettings().extraInterfaces(Bar.class, Baz.class));
55      *
56      *   //now, the mock implements extra interfaces, so following casting is possible:
57      *   Bar bar = (Bar) foo;
58      *   Baz baz = (Baz) foo;
59      * </code></pre>
60      *
61      * @param interfaces extra interfaces the should implement.
62      * @return settings instance so that you can fluently specify other settings
63      */
extraInterfaces(Class<?>.... interfaces)64     MockSettings extraInterfaces(Class<?>... interfaces);
65 
66     /**
67      * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
68      * <p>
69      * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
70      * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
71      * <p>
72      * <b>If you use &#064;Mock annotation then you've got naming mocks for free!</b> &#064;Mock uses field name as mock name. {@link Mock Read more.}
73      * <p>
74      * Examples:
75      * <pre class="code"><code class="java">
76      *   Foo foo = mock(Foo.class, withSettings().name("foo"));
77      *
78      *   //Below does exactly the same:
79      *   Foo foo = mock(Foo.class, "foo");
80      * </code></pre>
81      * @param name the name of the mock, later used in all verification errors
82      * @return settings instance so that you can fluently specify other settings
83      */
name(String name)84     MockSettings name(String name);
85 
86     /**
87      * Specifies the instance to spy on. Makes sense only for spies/partial mocks.
88      *
89      * Sets the instance that will be spied. Actually copies the internal fields of the passed instance to the mock.
90      * <p>
91      * As usual you are going to read <b>the partial mock warning</b>:
92      * Object oriented programming is more or less about tackling complexity by dividing the complexity into separate, specific, SRPy objects.
93      * How does partial mock fit into this paradigm? Well, it just doesn't...
94      * Partial mock usually means that the complexity has been moved to a different method on the same object.
95      * In most cases, this is not the way you want to design your application.
96      * <p>
97      * However, there are rare cases when partial mocks come handy:
98      * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
99      * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
100      * <p>
101      * Enough warnings about partial mocks, see an example how spiedInstance() works:
102      * <pre class="code"><code class="java">
103      *   Foo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance));
104      *
105      *   //Below does exactly the same:
106      *   Foo foo = spy(fooInstance);
107      * </code></pre>
108      *
109      * About stubbing for a partial mock, as it is a spy it will always call the real method, unless you use the
110      * <code>doReturn</code>|<code>Throw</code>|<code>Answer</code>|<code>CallRealMethod</code> stubbing style. Example:
111      *
112      * <pre class="code"><code class="java">
113      *   List list = new LinkedList();
114      *   List spy = spy(list);
115      *
116      *   //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
117      *   when(spy.get(0)).thenReturn("foo");
118      *
119      *   //You have to use doReturn() for stubbing
120      *   doReturn("foo").when(spy).get(0);
121      * </code>
122      *
123      * @param instance to spy on
124      * @return settings instance so that you can fluently specify other settings
125      */
spiedInstance(Object instance)126     MockSettings spiedInstance(Object instance);
127 
128     /**
129      * Specifies default answers to interactions.
130      * It's quite advanced feature and typically you don't need it to write decent tests.
131      * However it can be helpful when working with legacy systems.
132      * <p>
133      * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
134      *
135      * <pre class="code"><code class="java">
136      *   Foo mock = mock(Foo.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
137      *   Foo mockTwo = mock(Foo.class, withSettings().defaultAnswer(new YourOwnAnswer()));
138      *
139      *   //Below does exactly the same:
140      *   Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
141      * </code></pre>
142      *
143      * @param defaultAnswer default answer to be used by mock when not stubbed
144      * @return settings instance so that you can fluently specify other settings
145      */
146     @SuppressWarnings("unchecked")
defaultAnswer(Answer defaultAnswer)147     MockSettings defaultAnswer(Answer defaultAnswer);
148 
149     /**
150      * Configures the mock to be serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
151      * <p>
152      * WARNING: This should be rarely used in unit testing.
153      * <p>
154      * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency.  This
155      * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
156      * <p>
157      * Example:
158      * <pre class="code"><code class="java">
159      *   List serializableMock = mock(List.class, withSettings().serializable());
160      * </code></pre>
161      *
162      * @return settings instance so that you can fluently specify other settings
163      * @since 1.8.1
164      */
serializable()165     MockSettings serializable();
166 
167     /**
168      * Configures the mock to be serializable with a specific serializable mode.
169      * With this feature you can use a mock in a place that requires dependencies to be serializable.
170      * <p>
171      * WARNING: This should be rarely used in unit testing.
172      * <p>
173      * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency.  This
174      * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
175      *
176      * <pre class="code"><code class="java">
177      *   List serializableMock = mock(List.class, withSettings().serializable(SerializableMode.ACROSS_CLASSLOADERS));
178      * </code></pre>
179      *
180      * @param mode serialization mode
181      * @return settings instance so that you can fluently specify other settings
182      * @since 1.10.0
183      */
serializable(SerializableMode mode)184     MockSettings serializable(SerializableMode mode);
185 
186     /**
187      * Enables real-time logging of method invocations on this mock. Can be used
188      * during test debugging in order to find wrong interactions with this mock.
189      * <p>
190      * Invocations are logged as they happen to the standard output stream.
191      * <p>
192      * Calling this method multiple times makes no difference.
193      * <p>
194      * Example:
195      * <pre class="code"><code class="java">
196      * List mockWithLogger = mock(List.class, withSettings().verboseLogging());
197      * </code></pre>
198      *
199      * @return settings instance so that you can fluently specify other settings
200      */
verboseLogging()201     MockSettings verboseLogging();
202 
203     /**
204      * Registers a listener for method invocations on this mock. The listener is
205      * notified every time a method on this mock is called.
206      * <p>
207      * Multiple listeners may be added and they will be notified in the order they were supplied.
208      *
209      * Example:
210      * <pre class="code"><code class="java">
211      *  List mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
212      * </code></pre>
213      *
214      * See the {@link InvocationListener listener interface} for more details.
215      *
216      * @param listeners The invocation listeners to add. May not be null.
217      * @return settings instance so that you can fluently specify other settings
218      */
invocationListeners(InvocationListener... listeners)219     MockSettings invocationListeners(InvocationListener... listeners);
220 
221     /**
222      * Registers a listener(s) that will be notified when user starts verification.
223      * See {@link VerificationStartedListener} on how such listener can be useful.
224      * <p>
225      * When multiple listeners are added, they are notified in order they were supplied.
226      * There is no reason to supply multiple listeners but we wanted to keep the API
227      * simple and consistent with {@link #invocationListeners(InvocationListener...)}.
228      * <p>
229      * Throws exception when any of the passed listeners is null or when the entire vararg array is null.
230      *
231      * @param listeners to be notified when user starts verification.
232      * @return settings instance so that you can fluently specify other settings
233      * @since 2.11.0
234      */
235     @Incubating
verificationStartedListeners(VerificationStartedListener... listeners)236     MockSettings verificationStartedListeners(VerificationStartedListener... listeners);
237 
238     /**
239      * A stub-only mock does not record method
240      * invocations, thus saving memory but
241      * disallowing verification of invocations.
242      * <p>
243      * Example:
244      * <pre class="code"><code class="java">
245      * List stubOnly = mock(List.class, withSettings().stubOnly());
246      * </code></pre>
247      *
248      * @return settings instance so that you can fluently specify other settings
249      */
stubOnly()250     MockSettings stubOnly();
251 
252     /**
253      * Mockito attempts to use constructor when creating instance of the mock.
254      * This is particularly useful for spying on abstract classes. See also {@link Mockito#spy(Class)}.
255      * <p>
256      * Example:
257      * <pre class="code"><code class="java">
258      * //Robust API, via settings builder:
259      * OtherAbstract spy = mock(OtherAbstract.class, withSettings()
260      *   .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
261      *
262      * //Mocking an abstract class with constructor arguments
263      * SomeAbstract spy = mock(SomeAbstract.class, withSettings()
264      *   .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));
265      *
266      * //Mocking a non-static inner abstract class:
267      * InnerAbstract spy = mock(InnerAbstract.class, withSettings()
268      *   .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
269      * </code></pre>
270      *
271      * @param args The arguments to pass to the constructor. Not passing any arguments means that a parameter-less
272      *             constructor will be called
273      * @return settings instance so that you can fluently specify other settings
274      * @since 2.7.14 (useConstructor with no arguments was supported since 1.10.12)
275      */
276     @Incubating
useConstructor(Object... args)277     MockSettings useConstructor(Object... args);
278 
279     /**
280      * Makes it possible to mock non-static inner classes in conjunction with {@link #useConstructor(Object...)}.
281      * <p>
282      * Example:
283      * <pre class="code"><code class="java">
284      * InnerClass mock = mock(InnerClass.class, withSettings()
285      *   .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
286      * </code></pre>
287      *
288      * @return settings instance so that you can fluently specify other settings
289      * @since 1.10.12
290      */
291     @Incubating
outerInstance(Object outerClassInstance)292     MockSettings outerInstance(Object outerClassInstance);
293 
294     /**
295      * By default, Mockito makes an attempt to preserve all annotation meta data on the mocked
296      * type and its methods to mirror the mocked type as closely as possible. If this is not
297      * desired, this option can be used to disable this behavior.
298      *
299      * @return settings instance so that you can fluently specify other settings
300      * @since 1.10.13
301      */
302     @Incubating
withoutAnnotations()303     MockSettings withoutAnnotations();
304 
305     /**
306      * Creates immutable view of mock settings used later by Mockito.
307      * Framework integrators can use this method to create instances of creation settings
308      * and use them in advanced use cases, for example to create invocations with {@link InvocationFactory},
309      * or to implement custom {@link MockHandler}.
310      * Since {@link MockCreationSettings} is {@link NotExtensible}, Mockito public API needs a creation method for this type.
311      *
312      * @param typeToMock class to mock
313      * @param <T> type to mock
314      * @return immutable view of mock settings
315      * @since 2.10.0
316      */
317     @Incubating
build(Class<T> typeToMock)318     <T> MockCreationSettings<T> build(Class<T> typeToMock);
319 }
320