1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5package org.mockito; 6 7import java.lang.annotation.Documented; 8import java.lang.annotation.Retention; 9import java.lang.annotation.Target; 10 11import static java.lang.annotation.ElementType.FIELD; 12import static java.lang.annotation.RetentionPolicy.RUNTIME; 13 14/** 15 * Mark a field as a mock. 16 * 17 * <ul> 18 * <li>Allows shorthand mock creation.</li> 19 * <li>Minimizes repetitive mock creation code.</li> 20 * <li>Makes the test class more readable.</li> 21 * <li>Makes the verification error easier to read because the <b>field name</b> is used to identify the mock.</li> 22 * </ul> 23 * 24 * <pre class="code"><code class="java"> 25 * public class ArticleManagerTest extends SampleBaseTestCase { 26 * 27 * @Mock private ArticleCalculator calculator; 28 * @Mock(name = "database") private ArticleDatabase dbMock; 29 * @Mock(answer = RETURNS_MOCKS) private UserProvider userProvider; 30 * @Mock(extraInterfaces = {Queue.class, Observer.class}) private articleMonitor; 31 * 32 * private ArticleManager manager; 33 * 34 * @Before public void setup() { 35 * manager = new ArticleManager(userProvider, database, calculator, articleMonitor); 36 * } 37 * } 38 * 39 * public class SampleBaseTestCase { 40 * 41 * @Before public void initMocks() { 42 * MockitoAnnotations.initMocks(this); 43 * } 44 * } 45 * </code></pre> 46 * 47 * <p> 48 * <strong><code>MockitoAnnotations.initMocks(this)</code></strong> method has to be called to initialize annotated objects. 49 * In above example, <code>initMocks()</code> is called in @Before (JUnit4) method of test's base class. 50 * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class. 51 * <strong>Instead</strong> you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in 52 * {@link org.mockito.runners.MockitoJUnitRunner}. 53 * </p> 54 * 55 * @see Mockito#mock(Class) 56 * @see Spy 57 * @see InjectMocks 58 * @see MockitoAnnotations#initMocks(Object) 59 * @see org.mockito.runners.MockitoJUnitRunner 60 */ 61@Target(FIELD) 62@Retention(RUNTIME) 63@Documented 64public @interface Mock { 65 66 Answers answer() default Answers.RETURNS_DEFAULTS; 67 68 String name() default ""; 69 70 Class<?>[] extraInterfaces() default {}; 71 72 boolean serializable() default false; 73} 74