1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 6 package org.mockito; 7 8 import org.mockito.exceptions.base.MockitoException; 9 import org.mockito.internal.configuration.GlobalConfiguration; 10 import org.mockito.junit.MockitoJUnitRunner; 11 import org.mockito.plugins.AnnotationEngine; 12 13 /** 14 * MockitoAnnotations.initMocks(this); initializes fields annotated with Mockito annotations. 15 * See also {@link MockitoSession} which not only initializes mocks 16 * but also adds extra validation for cleaner tests! 17 * <p> 18 * <ul> 19 * <li>Allows shorthand creation of objects required for testing.</li> 20 * <li>Minimizes repetitive mock creation code.</li> 21 * <li>Makes the test class more readable.</li> 22 * <li>Makes the verification error easier to read because <b>field name</b> is used to identify the mock.</li> 23 * </ul> 24 * 25 * <pre class="code"><code class="java"> 26 * public class ArticleManagerTest extends SampleBaseTestCase { 27 * 28 * @Mock private ArticleCalculator calculator; 29 * @Mock private ArticleDatabase database; 30 * @Mock private UserProvider userProvider; 31 * 32 * private ArticleManager manager; 33 * 34 * @Before public void setup() { 35 * manager = new ArticleManager(userProvider, database, calculator); 36 * } 37 * } 38 * 39 * public class SampleBaseTestCase { 40 * 41 * @Before public void initMocks() { 42 * MockitoAnnotations.initMocks(this); 43 * } 44 * } 45 * </code></pre> 46 * <p> 47 * Read also about other annotations @{@link Spy}, @{@link Captor}, @{@link InjectMocks} 48 * <p> 49 * <b><code>MockitoAnnotations.initMocks(this)</code></b> method has to called to initialize annotated fields. 50 * <p> 51 * In above example, <code>initMocks()</code> is called in @Before (JUnit4) method of test's base class. 52 * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class. 53 * You can also put initMocks() in your JUnit runner (@RunWith) or use built-in runner: {@link MockitoJUnitRunner} 54 */ 55 public class MockitoAnnotations { 56 57 /** 58 * Initializes objects annotated with Mockito annotations for given testClass: 59 * @{@link org.mockito.Mock}, @{@link Spy}, @{@link Captor}, @{@link InjectMocks} 60 * <p> 61 * See examples in javadoc for {@link MockitoAnnotations} class. 62 */ initMocks(Object testClass)63 public static void initMocks(Object testClass) { 64 if (testClass == null) { 65 throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class"); 66 } 67 68 AnnotationEngine annotationEngine = new GlobalConfiguration().tryGetPluginAnnotationEngine(); 69 annotationEngine.process(testClass.getClass(), testClass); 70 } 71 } 72