Package org.mockito
Class MockitoAnnotations
- java.lang.Object
-
- org.mockito.MockitoAnnotations
-
public class MockitoAnnotations extends java.lang.Object
MockitoAnnotations.initMocks(this); initializes fields annotated with Mockito annotations. See alsoMockitoSession
which not only initializes mocks but also adds extra validation for cleaner tests!- Allows shorthand creation of objects required for testing.
- Minimizes repetitive mock creation code.
- Makes the test class more readable.
- Makes the verification error easier to read because field name is used to identify the mock.
public class ArticleManagerTest extends SampleBaseTestCase { @Mock private ArticleCalculator calculator; @Mock private ArticleDatabase database; @Mock private UserProvider userProvider; private ArticleManager manager; @Before public void setup() { manager = new ArticleManager(userProvider, database, calculator); } } public class SampleBaseTestCase { @Before public void initMocks() { MockitoAnnotations.initMocks(this); } }
Read also about other annotations @
Spy
, @Captor
, @InjectMocks
MockitoAnnotations.initMocks(this)
method has to be called to initialize annotated fields.In above example,
initMocks()
is called in @Before (JUnit4) method of test's base class. For JUnit3initMocks()
can go tosetup()
method of a base class. You can also put initMocks() in your JUnit runner (@RunWith) or use built-in runner:MockitoJUnitRunner
-
-
Constructor Summary
Constructors Constructor Description MockitoAnnotations()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
initMocks(java.lang.Object testClass)
Initializes objects annotated with Mockito annotations for given testClass: @Mock
, @Spy
, @Captor
, @InjectMocks
-
-
-
Method Detail
-
initMocks
public static void initMocks(java.lang.Object testClass)
Initializes objects annotated with Mockito annotations for given testClass: @Mock
, @Spy
, @Captor
, @InjectMocks
See examples in javadoc for
MockitoAnnotations
class.
-
-