Class | Line # | Actions | |||||
---|---|---|---|---|---|---|---|
MockitoTestCase | 45 | 29 | 0% | 30 | 54 |
1 | /* | |
2 | * Licensed to the Apache Software Foundation (ASF) under one | |
3 | * or more contributor license agreements. See the NOTICE file | |
4 | * distributed with this work for additional information | |
5 | * regarding copyright ownership. The ASF licenses this file | |
6 | * to you under the Apache License, Version 2.0 (the | |
7 | * "License"); you may not use this file except in compliance | |
8 | * with the License. You may obtain a copy of the License at | |
9 | * | |
10 | * http://www.apache.org/licenses/LICENSE-2.0 | |
11 | * | |
12 | * Unless required by applicable law or agreed to in writing, | |
13 | * software distributed under the License is distributed on an | |
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
15 | * KIND, either express or implied. See the License for the | |
16 | * specific language governing permissions and limitations | |
17 | * under the License. | |
18 | */ | |
19 | package org.devacfr.testing.jupiter; | |
20 | ||
21 | import org.junit.jupiter.api.extension.ExtendWith; | |
22 | import org.mockito.ArgumentCaptor; | |
23 | import org.mockito.ArgumentMatcher; | |
24 | import org.mockito.ArgumentMatchers; | |
25 | import org.mockito.InOrder; | |
26 | import org.mockito.Mock; | |
27 | import org.mockito.MockSettings; | |
28 | import org.mockito.Mockito; | |
29 | import org.mockito.junit.jupiter.MockitoExtension; | |
30 | import org.mockito.stubbing.Answer; | |
31 | import org.mockito.stubbing.OngoingStubbing; | |
32 | import org.mockito.stubbing.Stubber; | |
33 | import org.mockito.verification.VerificationMode; | |
34 | import org.mockito.verification.VerificationWithTimeout; | |
35 | ||
36 | /** | |
37 | * <p> | |
38 | * This class allow to migrate form JUnit 3.x syntax to JUnit 4. | |
39 | * </p> | |
40 | * it is also Mock facility. | |
41 | * | |
42 | * @author Christophe Friederich | |
43 | */ | |
44 | @ExtendWith(MockitoExtension.class) | |
45 | public abstract class MockitoTestCase extends TestCase { | |
46 | ||
47 | /** | |
48 | * | |
49 | */ | |
50 | 23 | public MockitoTestCase() { |
51 | } | |
52 | ||
53 | /** | |
54 | * any object or null. | |
55 | * <p> | |
56 | * Shorter alias to {@link Matchers#anyObject()} | |
57 | * <p> | |
58 | * See examples in javadoc for {@link Matchers} class | |
59 | * | |
60 | * @return <code>null</code>. | |
61 | */ | |
62 | 0 | @SuppressWarnings("unchecked") |
63 | protected static <T> T any() { | |
64 | 0 | return (T) ArgumentMatchers.any(); |
65 | } | |
66 | ||
67 | /** | |
68 | * Object argument that is equal to the given value. | |
69 | * <p> | |
70 | * See examples in javadoc for {@link Matchers} class | |
71 | * | |
72 | * @param value | |
73 | * the given value. | |
74 | * @return <code>null</code>. | |
75 | */ | |
76 | 0 | protected static <T> T eq(final T cl) { |
77 | 0 | return ArgumentMatchers.eq(cl); |
78 | } | |
79 | ||
80 | /** | |
81 | * any object or null. | |
82 | * <p> | |
83 | * Shorter alias to {@link Matchers#anyObject()} | |
84 | * <p> | |
85 | * See examples in javadoc for {@link Matchers} class | |
86 | * | |
87 | * @return <code>null</code>. | |
88 | */ | |
89 | 77 | protected static <T> T any(final Class<T> cl) { |
90 | 77 | return ArgumentMatchers.any(cl); |
91 | } | |
92 | ||
93 | /** | |
94 | * Creates mock object of given class or interface. | |
95 | * <p> | |
96 | * See examples in javadoc for {@link Mockito} class | |
97 | * | |
98 | * @param classToMock | |
99 | * class or interface to mock | |
100 | * @return mock object | |
101 | */ | |
102 | 0 | protected static <T> T mock(final Class<T> classToMock) { |
103 | 0 | return Mockito.mock(classToMock); |
104 | } | |
105 | ||
106 | /** | |
107 | * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors. | |
108 | * <p> | |
109 | * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. <b>If you | |
110 | * have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks. | |
111 | * <p> | |
112 | * <b>If you use @Mock annotation then you've got naming mocks for free!</b> @Mock uses field name as mock | |
113 | * name. {@link Mock Read more.} | |
114 | * <p> | |
115 | * See examples in javadoc for {@link Mockito} class | |
116 | * | |
117 | * @param classToMock | |
118 | * class or interface to mock | |
119 | * @param name | |
120 | * of the mock | |
121 | * @return mock object | |
122 | */ | |
123 | 0 | protected static <T> T mock(final Class<T> classToMock, final String name) { |
124 | 0 | return Mockito.mock(classToMock, name); |
125 | } | |
126 | ||
127 | /** | |
128 | * Creates mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically | |
129 | * you don't need it to write decent tests. However it can be helpful when working with legacy systems. | |
130 | * <p> | |
131 | * It is the default answer so it will be used <b>only when you don't</b> stub the method call. | |
132 | * | |
133 | * <pre> | |
134 | * | |
135 | * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); | |
136 | * | |
137 | * Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); | |
138 | * </pre> | |
139 | * <p> | |
140 | * See examples in javadoc for {@link Mockito} class | |
141 | * </p> | |
142 | * | |
143 | * @param classToMock | |
144 | * class or interface to mock | |
145 | * @param defaultAnswer | |
146 | * default answer for unstubbed methods | |
147 | * @return mock object | |
148 | */ | |
149 | 0 | protected static <T> T mock(final Class<T> classToMock, final Answer<?> defaultAnswer) { |
150 | 0 | return Mockito.mock(classToMock, defaultAnswer); |
151 | } | |
152 | ||
153 | /** | |
154 | * Creates a mock with some non-standard settings. | |
155 | * <p> | |
156 | * The number of configuration points for a mock grows so we need a fluent way to introduce new configuration | |
157 | * without adding more and more overloaded Mockito.mock() methods. Hence {@link MockSettings}. | |
158 | * | |
159 | * <pre> | |
160 | * Listener mock = mock(Listener.class, withSettings() | |
161 | * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); | |
162 | * ); | |
163 | * </pre> | |
164 | * | |
165 | * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks? Is the code | |
166 | * under test so complicated that it requires non-standard mocks? Wouldn't you prefer to refactor the code under | |
167 | * test so it is testable in a simple way? | |
168 | * <p> | |
169 | * See also {@link Mockito#withSettings()} | |
170 | * <p> | |
171 | * See examples in javadoc for {@link Mockito} class | |
172 | * | |
173 | * @param classToMock | |
174 | * class or interface to mock | |
175 | * @param mockSettings | |
176 | * additional mock settings | |
177 | * @return mock object | |
178 | */ | |
179 | 0 | protected static <T> T mock(final Class<T> classToMock, final MockSettings mockSettings) { |
180 | 0 | return Mockito.mock(classToMock, mockSettings); |
181 | } | |
182 | ||
183 | /** | |
184 | * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed. | |
185 | * <p> | |
186 | * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. | |
187 | * <p> | |
188 | * As usual you are going to read <b>the partial mock warning</b>: Object oriented programming is more less tackling | |
189 | * complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this | |
190 | * paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different | |
191 | * method on the same object. In most cases, this is not the way you want to design your application. | |
192 | * <p> | |
193 | * However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd | |
194 | * party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, | |
195 | * test-driven & well-designed code. | |
196 | * <p> | |
197 | * Example: | |
198 | * | |
199 | * <pre> | |
200 | * List list = new LinkedList(); | |
201 | * List spy = spy(list); | |
202 | * | |
203 | * // optionally, you can stub out some methods: | |
204 | * when(spy.size()).thenReturn(100); | |
205 | * | |
206 | * // using the spy calls <b>real</b> methods | |
207 | * spy.add("one"); | |
208 | * spy.add("two"); | |
209 | * | |
210 | * // prints "one" - the first element of a list | |
211 | * System.out.println(spy.get(0)); | |
212 | * | |
213 | * // size() method was stubbed - 100 is printed | |
214 | * System.out.println(spy.size()); | |
215 | * | |
216 | * // optionally, you can verify | |
217 | * verify(spy).add("one"); | |
218 | * verify(spy).add("two"); | |
219 | * </pre> | |
220 | * | |
221 | * <h4>Important gotcha on spying real objects!</h4> 1. Sometimes it's impossible to use | |
222 | * {@link Mockito#when(Object)} for stubbing spies. Example: | |
223 | * | |
224 | * <pre> | |
225 | * List list = new LinkedList(); | |
226 | * List spy = spy(list); | |
227 | * | |
228 | * // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) | |
229 | * when(spy.get(0)).thenReturn("foo"); | |
230 | * | |
231 | * // You have to use doReturn() for stubbing | |
232 | * doReturn("foo").when(spy).get(0); | |
233 | * </pre> | |
234 | * | |
235 | * 2. Watch out for final methods. Mockito doesn't mock final methods so the bottom line is: when you spy on real | |
236 | * objects + you try to stub a final method = trouble. What will happen is the real method will be called *on mock* | |
237 | * but *not on the real instance* you passed to the spy() method. Typically you may get a NullPointerException | |
238 | * because mock instances don't have fields initiated. | |
239 | * <p> | |
240 | * See examples in javadoc for {@link Mockito} class | |
241 | * | |
242 | * @param object | |
243 | * to spy on | |
244 | * @return a spy of the real object | |
245 | */ | |
246 | 0 | protected static <T> T spy(final T object) { |
247 | 0 | return Mockito.spy(object); |
248 | } | |
249 | ||
250 | /** | |
251 | * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is | |
252 | * called. | |
253 | * <p> | |
254 | * Simply put: "<b>When</b> the x method is called <b>then</b> return y". | |
255 | * <p> | |
256 | * <b>when() is a successor of deprecated {@link Mockito#stub(Object)}</b> | |
257 | * <p> | |
258 | * Examples: | |
259 | * | |
260 | * <pre> | |
261 | * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10); | |
262 | * | |
263 | * //you can use flexible argument matchers, e.g: | |
264 | * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10); | |
265 | * | |
266 | * //setting exception to be thrown: | |
267 | * when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); | |
268 | * | |
269 | * //you can set different behavior for consecutive method calls. | |
270 | * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. | |
271 | * when(mock.someMethod("some arg")) | |
272 | * .thenThrow(new RuntimeException()) | |
273 | * .thenReturn("foo"); | |
274 | * | |
275 | * //Alternative, shorter version for consecutive stubbing: | |
276 | * when(mock.someMethod("some arg")) | |
277 | * .thenReturn("one", "two"); | |
278 | * //is the same as: | |
279 | * when(mock.someMethod("some arg")) | |
280 | * .thenReturn("one") | |
281 | * .thenReturn("two"); | |
282 | * | |
283 | * //shorter version for consecutive method calls throwing exceptions: | |
284 | * when(mock.someMethod("some arg")) | |
285 | * .thenThrow(new RuntimeException(), new NullPointerException(); | |
286 | * </pre> | |
287 | * | |
288 | * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable)} | |
289 | * <p> | |
290 | * Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override | |
291 | * it. Please note that overridding stubbing is a potential code smell that points out too much stubbing. | |
292 | * <p> | |
293 | * Once stubbed, the method will always return stubbed value regardless of how many times it is called. | |
294 | * <p> | |
295 | * Last stubbing is more important - when you stubbed the same method with the same arguments many times. | |
296 | * <p> | |
297 | * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. Let's say you've | |
298 | * stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even | |
299 | * verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not | |
300 | * convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>. | |
301 | * <p> | |
302 | * See examples in javadoc for {@link Mockito} class | |
303 | * | |
304 | * @param methodCall | |
305 | * method to be stubbed | |
306 | */ | |
307 | 63 | protected static <T> OngoingStubbing<T> when(final T methodCall) { |
308 | 63 | return Mockito.when(methodCall); |
309 | } | |
310 | ||
311 | /** | |
312 | * Verifies certain behavior <b>happened once</b> | |
313 | * <p> | |
314 | * Alias to <code>verify(mock, times(1))</code> E.g: | |
315 | * | |
316 | * <pre> | |
317 | * verify(mock).someMethod("some arg"); | |
318 | * </pre> | |
319 | * | |
320 | * Above is equivalent to: | |
321 | * | |
322 | * <pre> | |
323 | * verify(mock, times(1)).someMethod("some arg"); | |
324 | * </pre> | |
325 | * <p> | |
326 | * Arguments passed are compared using equals() method. Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} | |
327 | * to find out other ways of matching / asserting arguments passed. | |
328 | * <p> | |
329 | * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. Let's say you've | |
330 | * stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even | |
331 | * verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not | |
332 | * convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>. | |
333 | * <p> | |
334 | * See examples in javadoc for {@link Mockito} class | |
335 | * | |
336 | * @param mock | |
337 | * to be verified | |
338 | * @return mock object itself | |
339 | */ | |
340 | 0 | protected static <T> T verify(final T mock) { |
341 | 0 | return Mockito.verify(mock); |
342 | } | |
343 | ||
344 | /** | |
345 | * Verifies certain behavior happened at least once / exact number of times / never. E.g: | |
346 | * | |
347 | * <pre> | |
348 | * verify(mock, times(5)).someMethod("was called five times"); | |
349 | * | |
350 | * verify(mock, atLeast(2)).someMethod("was called at least two times"); | |
351 | * | |
352 | * //you can use flexible argument matchers, e.g: | |
353 | * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>); | |
354 | * </pre> | |
355 | * | |
356 | * <b>times(1) is the default</b> and can be omitted | |
357 | * <p> | |
358 | * Arguments passed are compared using equals() method. Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} | |
359 | * to find out other ways of matching / asserting arguments passed. | |
360 | * <p> | |
361 | * | |
362 | * @param mock | |
363 | * to be verified | |
364 | * @param mode | |
365 | * times(x), atLeastOnce() or never() | |
366 | * @return mock object itself | |
367 | */ | |
368 | 0 | protected static <T> T verify(final T mock, final VerificationMode mode) { |
369 | 0 | return Mockito.verify(mock, mode); |
370 | } | |
371 | ||
372 | /** | |
373 | * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you | |
374 | * don't need to reset your mocks, just create new mocks for each test method. | |
375 | * <p> | |
376 | * Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified | |
377 | * tests. <b>First potential code smell is reset() in the middle of the test method.</b> This probably means you're | |
378 | * testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior". | |
379 | * There are several threads about it on mockito mailing list. | |
380 | * <p> | |
381 | * The only reason we added reset() method is to make it possible to work with container-injected mocks. See issue | |
382 | * 55 (<a href="http://code.google.com/p/mockito/issues/detail?id=55">here</a>) or FAQ ( | |
383 | * <a href="http://code.google.com/p/mockito/wiki/FAQ">here</a>). | |
384 | * <p> | |
385 | * <b>Don't harm yourself.</b> reset() in the middle of the test method is a code smell (you're probably testing too | |
386 | * much). | |
387 | * | |
388 | * <pre> | |
389 | * List mock = mock(List.class); | |
390 | * when(mock.size()).thenReturn(10); | |
391 | * mock.add(1); | |
392 | * | |
393 | * reset(mock); | |
394 | * // at this point the mock forgot any interactions & stubbing | |
395 | * </pre> | |
396 | * | |
397 | * @param <T> | |
398 | * @param mocks | |
399 | * to be reset | |
400 | */ | |
401 | 0 | @SuppressWarnings("unchecked") |
402 | protected static <T> void reset(final T... mocks) { | |
403 | 0 | Mockito.reset(mocks); |
404 | } | |
405 | ||
406 | /** | |
407 | * Checks if any of given mocks has any unverified interaction. | |
408 | * <p> | |
409 | * You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks. | |
410 | * <p> | |
411 | * See also {@link Mockito#never()} - it is more explicit and communicates the intent well. | |
412 | * <p> | |
413 | * Stubbed invocations (if called) are also treated as interactions. | |
414 | * <p> | |
415 | * A word of <b>warning</b>: Some users who did a lot of classic, expect-run-verify mocking tend to use | |
416 | * verifyNoMoreInteractions() very often, even in every test method. verifyNoMoreInteractions() is not recommended | |
417 | * to use in every test method. verifyNoMoreInteractions() is a handy assertion from the interaction testing | |
418 | * toolkit. Use it only when it's relevant. Abusing it leads to overspecified, less maintainable tests. You can find | |
419 | * further reading <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>. | |
420 | * <p> | |
421 | * This method will also detect unverified invocations that occurred before the test method, for example: in | |
422 | * setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test | |
423 | * methods. | |
424 | * <p> | |
425 | * Example: | |
426 | * | |
427 | * <pre> | |
428 | * // interactions | |
429 | * mock.doSomething(); | |
430 | * mock.doSomethingUnexpected(); | |
431 | * | |
432 | * // verification | |
433 | * verify(mock).doSomething(); | |
434 | * | |
435 | * // following will fail because 'doSomethingUnexpected()' is unexpected | |
436 | * verifyNoMoreInteractions(mock); | |
437 | * | |
438 | * </pre> | |
439 | * | |
440 | * See examples in javadoc for {@link Mockito} class | |
441 | * | |
442 | * @param mocks | |
443 | * to be verified | |
444 | */ | |
445 | 0 | protected static void verifyNoMoreInteractions(final Object... mocks) { |
446 | 0 | Mockito.verifyNoMoreInteractions(mocks); |
447 | } | |
448 | ||
449 | /** | |
450 | * Use doThrow() when you want to stub the void method with an exception. | |
451 | * <p> | |
452 | * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like | |
453 | * void methods inside brackets... | |
454 | * <p> | |
455 | * Example: | |
456 | * | |
457 | * <pre> | |
458 | * doThrow(new RuntimeException()).when(mock).someVoidMethod(); | |
459 | * </pre> | |
460 | * | |
461 | * @param toBeThrown | |
462 | * to be thrown when the stubbed method is called | |
463 | * @return stubber - to select a method for stubbing | |
464 | */ | |
465 | 0 | protected Stubber doThrow(final Throwable toBeThrown) { |
466 | 0 | return Mockito.doThrow(toBeThrown); |
467 | } | |
468 | ||
469 | /** | |
470 | * Use <code>doThrow()</code> when you want to stub the void method to throw exception of specified class. | |
471 | * <p> | |
472 | * A new exception instance will be created for each method invocation. | |
473 | * <p> | |
474 | * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like | |
475 | * void methods inside brackets... | |
476 | * <p> | |
477 | * Example: | |
478 | * | |
479 | * <pre class="code"> | |
480 | * <code class="java"> | |
481 | * doThrow(RuntimeException.class).when(mock).someVoidMethod(); | |
482 | * </code> | |
483 | * </pre> | |
484 | * | |
485 | * @param toBeThrown | |
486 | * to be thrown when the stubbed method is called | |
487 | * @return stubber - to select a method for stubbing | |
488 | */ | |
489 | 0 | public static Stubber doThrow(final Class<? extends Throwable> toBeThrown) { |
490 | 0 | return Mockito.doThrow(toBeThrown); |
491 | } | |
492 | ||
493 | /** | |
494 | * Use doCallRealMethod() when you want to call the real implementation of a method. | |
495 | * <p> | |
496 | * As usual you are going to read <b>the partial mock warning</b>: Object oriented programming is more less tackling | |
497 | * complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this | |
498 | * paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different | |
499 | * method on the same object. In most cases, this is not the way you want to design your application. | |
500 | * <p> | |
501 | * However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd | |
502 | * party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, | |
503 | * test-driven & well-designed code. | |
504 | * <p> | |
505 | * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks. <b>Mockito.spy() is a | |
506 | * recommended way of creating partial mocks.</b> The reason is it guarantees real methods are called against | |
507 | * correctly constructed object because you're responsible for constructing the object passed to spy() method. | |
508 | * <p> | |
509 | * Example: | |
510 | * | |
511 | * <pre> | |
512 | * Foo mock = mock(Foo.class); | |
513 | * doCallRealMethod().when(mock).someVoidMethod(); | |
514 | * | |
515 | * // this will call the real implementation of Foo.someVoidMethod() | |
516 | * mock.someVoidMethod(); | |
517 | * </pre> | |
518 | * <p> | |
519 | * See examples in javadoc for {@link Mockito} class | |
520 | * | |
521 | * @return stubber - to select a method for stubbing | |
522 | */ | |
523 | 0 | protected static Stubber doCallRealMethod() { |
524 | 0 | return Mockito.doCallRealMethod(); |
525 | } | |
526 | ||
527 | /** | |
528 | * Use doAnswer() when you want to stub a void method with generic {@link Answer}. | |
529 | * <p> | |
530 | * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like | |
531 | * void methods inside brackets... | |
532 | * <p> | |
533 | * Example: | |
534 | * | |
535 | * <pre> | |
536 | * doAnswer(new Answer() { | |
537 | * | |
538 | * public Object answer(InvocationOnMock invocation) { | |
539 | * Object[] args = invocation.getArguments(); | |
540 | * Mock mock = invocation.getMock(); | |
541 | * return null; | |
542 | * } | |
543 | * }).when(mock).someMethod(); | |
544 | * </pre> | |
545 | * <p> | |
546 | * See examples in javadoc for {@link Mockito} class | |
547 | * | |
548 | * @param answer | |
549 | * to answer when the stubbed method is called | |
550 | * @return stubber - to select a method for stubbing | |
551 | */ | |
552 | 0 | protected static Stubber doAnswer(final Answer<?> answer) { |
553 | 0 | return Mockito.doAnswer(answer); |
554 | } | |
555 | ||
556 | /** | |
557 | * Use doNothing() for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by | |
558 | * default!</b> However, there are rare situations when doNothing() comes handy: | |
559 | * <p> | |
560 | * 1. Stubbing consecutive calls on a void method: | |
561 | * | |
562 | * <pre> | |
563 | * doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod(); | |
564 | * | |
565 | * // does nothing the first time: | |
566 | * mock.someVoidMethod(); | |
567 | * | |
568 | * // throws RuntimeException the next time: | |
569 | * mock.someVoidMethod(); | |
570 | * </pre> | |
571 | * | |
572 | * 2. When you spy real objects and you want the void method to do nothing: | |
573 | * | |
574 | * <pre> | |
575 | * List list = new LinkedList(); | |
576 | * List spy = spy(list); | |
577 | * | |
578 | * // let's make clear() do nothing | |
579 | * doNothing().when(spy).clear(); | |
580 | * | |
581 | * spy.add("one"); | |
582 | * | |
583 | * // clear() does nothing, so the list still contains "one" | |
584 | * spy.clear(); | |
585 | * </pre> | |
586 | * <p> | |
587 | * See examples in javadoc for {@link Mockito} class | |
588 | * | |
589 | * @return stubber - to select a method for stubbing | |
590 | */ | |
591 | 0 | protected static Stubber doNothing() { |
592 | 0 | return Mockito.doNothing(); |
593 | } | |
594 | ||
595 | /** | |
596 | * Use doReturn() in those rare occasions when you cannot use {@link Mockito#when(Object)}. | |
597 | * <p> | |
598 | * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe | |
599 | * and more readable</b> (especially when stubbing consecutive calls). | |
600 | * <p> | |
601 | * Here are those rare occasions when doReturn() comes handy: | |
602 | * <p> | |
603 | * 1. When spying real objects and calling real methods on a spy brings side effects | |
604 | * | |
605 | * <pre> | |
606 | * List list = new LinkedList(); | |
607 | * List spy = spy(list); | |
608 | * | |
609 | * // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) | |
610 | * when(spy.get(0)).thenReturn("foo"); | |
611 | * | |
612 | * // You have to use doReturn() for stubbing: | |
613 | * doReturn("foo").when(spy).get(0); | |
614 | * </pre> | |
615 | * | |
616 | * 2. Overriding a previous exception-stubbing: | |
617 | * | |
618 | * <pre> | |
619 | * when(mock.foo()).thenThrow(new RuntimeException()); | |
620 | * | |
621 | * // Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. | |
622 | * when(mock.foo()).thenReturn("bar"); | |
623 | * | |
624 | * // You have to use doReturn() for stubbing: | |
625 | * doReturn("bar").when(mock).foo(); | |
626 | * </pre> | |
627 | * | |
628 | * Above scenarios shows a tradeoff of Mockito's ellegant syntax. Note that the scenarios are very rare, though. | |
629 | * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general | |
630 | * overridding stubbing is a potential code smell that points out too much stubbing. | |
631 | * <p> | |
632 | * See examples in javadoc for {@link Mockito} class | |
633 | * | |
634 | * @param toBeReturned | |
635 | * to be returned when the stubbed method is called | |
636 | * @return stubber - to select a method for stubbing | |
637 | */ | |
638 | 0 | protected static Stubber doReturn(final Object toBeReturned) { |
639 | 0 | return Mockito.doReturn(toBeReturned); |
640 | } | |
641 | ||
642 | /** | |
643 | * Creates InOrder object that allows verifying mocks in order. | |
644 | * | |
645 | * <pre> | |
646 | * InOrder inOrder = inOrder(firstMock, secondMock); | |
647 | * | |
648 | * inOrder.verify(firstMock).add("was called first"); | |
649 | * inOrder.verify(secondMock).add("was called second"); | |
650 | * </pre> | |
651 | * | |
652 | * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one but only those | |
653 | * that you are interested in testing in order. | |
654 | * <p> | |
655 | * Also, you can create InOrder object passing only mocks that are relevant for in-order verification. | |
656 | * <p> | |
657 | * InOrder verification is 'greedy'. You will hardly every notice it but if you want to find out more search for | |
658 | * 'greedy' on the Mockito <a href="http://code.google.com/p/mockito/w/list">wiki pages</a>. | |
659 | * <p> | |
660 | * As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: | |
661 | * {@link InOrder#verifyNoMoreInteractions()} | |
662 | * <p> | |
663 | * See examples in javadoc for {@link Mockito} class | |
664 | * | |
665 | * @param mocks | |
666 | * to be verified in order | |
667 | * @return InOrder object to be used to verify in order | |
668 | */ | |
669 | 0 | protected static InOrder inOrder(final Object... mocks) { |
670 | 0 | return Mockito.inOrder(mocks); |
671 | } | |
672 | ||
673 | /** | |
674 | * Allows verifying exact number of invocations. E.g: | |
675 | * | |
676 | * <pre> | |
677 | * verify(mock, times(2)).someMethod("some arg"); | |
678 | * </pre> | |
679 | * | |
680 | * See examples in javadoc for {@link Mockito} class | |
681 | * | |
682 | * @param wantedNumberOfInvocations | |
683 | * wanted number of invocations | |
684 | * @return verification mode | |
685 | */ | |
686 | 0 | protected VerificationMode times(final int wantedNumberOfInvocations) { |
687 | 0 | return Mockito.times(wantedNumberOfInvocations); |
688 | } | |
689 | ||
690 | /** | |
691 | * Alias to times(0), see {@link Mockito#times(int)} | |
692 | * <p> | |
693 | * Verifies that interaction did not happen. E.g: | |
694 | * | |
695 | * <pre> | |
696 | * verify(mock, never()).someMethod(); | |
697 | * </pre> | |
698 | * <p> | |
699 | * If you want to verify there were NO interactions with the mock check out | |
700 | * {@link Mockito#verifyZeroInteractions(Object...)} or {@link Mockito#verifyNoMoreInteractions(Object...)} | |
701 | * <p> | |
702 | * See examples in javadoc for {@link Mockito} class | |
703 | * | |
704 | * @return verification mode | |
705 | */ | |
706 | 0 | protected VerificationMode never() { |
707 | 0 | return Mockito.never(); |
708 | } | |
709 | ||
710 | /** | |
711 | * Allows at-least-once verification. E.g: | |
712 | * | |
713 | * <pre> | |
714 | * verify(mock, atLeastOnce()).someMethod("some arg"); | |
715 | * </pre> | |
716 | * | |
717 | * Alias to atLeast(1) | |
718 | * <p> | |
719 | * See examples in javadoc for {@link Mockito} class | |
720 | * | |
721 | * @return verification mode | |
722 | */ | |
723 | 0 | protected VerificationMode atLeastOnce() { |
724 | 0 | return Mockito.atLeastOnce(); |
725 | } | |
726 | ||
727 | /** | |
728 | * Allows at-least-x verification. E.g: | |
729 | * | |
730 | * <pre> | |
731 | * verify(mock, atLeast(3)).someMethod("some arg"); | |
732 | * </pre> | |
733 | * | |
734 | * See examples in javadoc for {@link Mockito} class | |
735 | * | |
736 | * @param minNumberOfInvocations | |
737 | * minimum number of invocations | |
738 | * @return verification mode | |
739 | */ | |
740 | 0 | protected static VerificationMode atLeast(final int minNumberOfInvocations) { |
741 | 0 | return Mockito.atLeast(minNumberOfInvocations); |
742 | } | |
743 | ||
744 | /** | |
745 | * Allows at-most-x verification. E.g: | |
746 | * | |
747 | * <pre> | |
748 | * verify(mock, atMost(3)).someMethod("some arg"); | |
749 | * </pre> | |
750 | * | |
751 | * See examples in javadoc for {@link Mockito} class | |
752 | * | |
753 | * @param maxNumberOfInvocations | |
754 | * max number of invocations | |
755 | * @return verification mode | |
756 | */ | |
757 | 0 | protected static VerificationMode atMost(final int maxNumberOfInvocations) { |
758 | 0 | return Mockito.atMost(maxNumberOfInvocations); |
759 | } | |
760 | ||
761 | /** | |
762 | * Allows checking if given method was the only one invoked. E.g: | |
763 | * | |
764 | * <pre> | |
765 | * verify(mock, only()).someMethod(); | |
766 | * // above is a shorthand for following 2 lines of code: | |
767 | * verify(mock).someMethod(); | |
768 | * verifyNoMoreInvocations(mock); | |
769 | * </pre> | |
770 | * <p> | |
771 | * See also {@link Mockito#verifyNoMoreInteractions(Object...)} | |
772 | * <p> | |
773 | * See examples in javadoc for {@link Mockito} class | |
774 | * | |
775 | * @return verification mode | |
776 | */ | |
777 | 0 | protected static VerificationMode only() { |
778 | 0 | return Mockito.only(); |
779 | } | |
780 | ||
781 | /** | |
782 | * Allows verifying with timeout. May be useful for testing in concurrent conditions. | |
783 | * <p> | |
784 | * It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system | |
785 | * <p> | |
786 | * Not yet implemented to work with InOrder verification. | |
787 | * | |
788 | * <pre> | |
789 | * // passes when someMethod() is called within given time span | |
790 | * verify(mock, timeout(100)).someMethod(); | |
791 | * // above is an alias to: | |
792 | * verify(mock, timeout(100).times(1)).someMethod(); | |
793 | * | |
794 | * // passes when someMethod() is called *exactly* 2 times within given time span | |
795 | * verify(mock, timeout(100).times(2)).someMethod(); | |
796 | * | |
797 | * // passes when someMethod() is called *at lest* 2 times within given time span | |
798 | * verify(mock, timeout(100).atLeast(2)).someMethod(); | |
799 | * | |
800 | * // verifies someMethod() within given time span using given verification mode | |
801 | * // useful only if you have your own custom verification modes. | |
802 | * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod(); | |
803 | * </pre> | |
804 | * | |
805 | * See examples in javadoc for {@link Mockito} class | |
806 | * | |
807 | * @param millis | |
808 | * - time span in millis | |
809 | * @return verification mode | |
810 | */ | |
811 | 0 | protected static VerificationWithTimeout timeout(final int millis) { |
812 | 0 | return Mockito.timeout(millis); |
813 | } | |
814 | ||
815 | /** | |
816 | * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: | |
817 | * <a href="http://code.google.com/p/mockito/wiki/FAQ">http://code.google.com/p/mockito/wiki/FAQ</a> | |
818 | * <p> | |
819 | * In case of questions you may also post to mockito mailing list: | |
820 | * <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a> | |
821 | * <p> | |
822 | * validateMockitoUsage() <b>explicitly validates</b> the framework state to detect invalid use of Mockito. However, | |
823 | * this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read | |
824 | * on. | |
825 | * <p> | |
826 | * Examples of incorrect use: | |
827 | * | |
828 | * <pre> | |
829 | * // Oups, someone forgot thenReturn() part: | |
830 | * when(mock.get()); | |
831 | * | |
832 | * // Oups, someone put the verified method call inside verify() where it should be outside: | |
833 | * verify(mock.execute()); | |
834 | * | |
835 | * // Oups, someone has used EasyMock for too long and forgot to specify the method to verify: | |
836 | * verify(mock); | |
837 | * </pre> | |
838 | * | |
839 | * Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. The gotcha is | |
840 | * that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call | |
841 | * mock etc.). But even though the exception might be thrown in the next test, the exception <b>message contains a | |
842 | * navigable stack trace element</b> with location of the defect. Hence you can click and find the place where | |
843 | * Mockito was misused. | |
844 | * <p> | |
845 | * Sometimes though, you might want to validate the framework usage explicitly. For example, one of the users wanted | |
846 | * to put validateMockitoUsage() in his @After method so that he knows immediately when he misused Mockito. | |
847 | * Without it, he would have known about it not sooner than <b>next time</b> he used the framework. One more benefit | |
848 | * of having validateMockitoUsage() in @After is that jUnit runner will always fail in the test method with | |
849 | * defect whereas ordinary 'next-time' validation might fail the <b>next</b> test method. But even though JUnit | |
850 | * might report next test as red, don't worry about it and just click at navigable stack trace element in the | |
851 | * exception message to instantly locate the place where you misused mockito. | |
852 | * <p> | |
853 | * <b>Built-in runner: {@link MockitoJUnitRunner}</b> does validateMockitoUsage() after each test method. | |
854 | * <p> | |
855 | * Bear in mind that <b>usually you don't have to validateMockitoUsage()</b> and framework validation triggered on | |
856 | * next-time basis should be just enough, mainly because of enhanced exception message with clickable location of | |
857 | * defect. However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure | |
858 | * (like your own runner or base class for all tests) because adding a special action to @After has zero cost. | |
859 | * <p> | |
860 | * See examples in javadoc for {@link Mockito} class | |
861 | */ | |
862 | 0 | protected static void validateMockitoUsage() { |
863 | 0 | Mockito.validateMockitoUsage(); |
864 | } | |
865 | ||
866 | /** | |
867 | * Allows mock creation with additional mock settings. | |
868 | * <p> | |
869 | * Don't use it too often. Consider writing simple tests that use simple mocks. Repeat after me: simple tests push | |
870 | * simple, KISSy, readable & maintainable code. If you cannot write a test in a simple way - refactor the code under | |
871 | * test. | |
872 | * <p> | |
873 | * Examples of mock settings: | |
874 | * | |
875 | * <pre> | |
876 | * | |
877 | * // Creates mock with different default answer & name | |
878 | * Foo mock = mock(Foo.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS).name("cool mockie")); | |
879 | * | |
880 | * // Creates mock with different default answer, descriptive name and extra interfaces | |
881 | * Foo mock = mock(Foo.class, | |
882 | * withSettings().defaultAnswer(RETURNS_SMART_NULLS).name("cool mockie").extraInterfaces(Bar.class)); | |
883 | * </pre> | |
884 | * | |
885 | * {@link MockSettings} has been introduced for two reasons. Firstly, to make it easy to add another mock settings | |
886 | * when the demand comes. Secondly, to enable combining different mock settings without introducing zillions of | |
887 | * overloaded mock() methods. | |
888 | * <p> | |
889 | * See javadoc for {@link MockSettings} to learn about possible mock settings. | |
890 | * <p> | |
891 | * | |
892 | * @return mock settings instance with defaults. | |
893 | */ | |
894 | 0 | protected static MockSettings withSettings() { |
895 | 0 | return Mockito.withSettings(); |
896 | } | |
897 | } |