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