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