Package org.mockito
Class MockitoAnnotations
java.lang.Object
org.mockito.MockitoAnnotations
MockitoAnnotations.openMocks(this); initializes fields annotated with Mockito annotations.
See also
MockitoSession
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 {
private AutoCloseable closeable;
@Before public void openMocks() {
closeable = MockitoAnnotations.openMocks(this);
}
@After public void releaseMocks() throws Exception {
closeable.close();
}
}
Read also about other annotations @Spy
, @Captor
, @InjectMocks
MockitoAnnotations.openMocks(this)
method has to be called to initialize annotated fields.
In above example, openMocks()
is called in @Before (JUnit4) method of test's base class.
You can also put openMocks() in your JUnit runner (@RunWith) or use built-in runner: MockitoJUnitRunner
.
If static method mocks are used, it is required to close the initialization. Additionally, if using third-party
mock-makers, other life-cycles might be handled by the open-release routine.
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
Deprecated.static AutoCloseable
Initializes objects annotated with Mockito annotations for given testClass: @Mock
, @Spy
, @Captor
, @InjectMocks
-
Method Details
-
openMocks
Initializes objects annotated with Mockito annotations for given testClass: @Mock
, @Spy
, @Captor
, @InjectMocks
See examples in javadoc for
MockitoAnnotations
class.- Returns:
- A closable to close when completing any tests in
testClass
.
-
initMocks
Deprecated.UseopenMocks(Object)
instead. This method is equivalent toopenMocks(testClass).close()
. The close method should however only be called after completed usage oftestClass
. If using static-mocks or customMockMaker
s, using this method might cause misbehavior of mocks injected into the test class.Initializes objects annotated with Mockito annotations for given testClass: @Mock
, @Spy
, @Captor
, @InjectMocks
See examples in javadoc for
MockitoAnnotations
class.
-
openMocks(Object)
instead.