public final class MockitoAnnotations extends Object
MockitoSession
which not only initializes mocks
but also adds extra validation for cleaner tests!
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.
For JUnit3 openMocks()
can go to setup()
method of a 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.
Modifier and Type | Method and Description |
---|---|
static void |
initMocks(Object testClass)
Deprecated.
Use
openMocks(Object) instead.
This method is equivalent to openMocks(testClass).close() .
The close method should however only be called after completed usage of testClass .
If using static-mocks or custom MockMaker s, using this method might
cause misbehavior of mocks injected into the test class. |
static AutoCloseable |
openMocks(Object testClass)
Initializes objects annotated with Mockito annotations for given testClass:
@
Mock , @Spy , @Captor , @InjectMocks |
public static AutoCloseable openMocks(Object testClass)
Mock
, @Spy
, @Captor
, @InjectMocks
See examples in javadoc for MockitoAnnotations
class.
testClass
.@Deprecated public static void initMocks(Object testClass)
openMocks(Object)
instead.
This method is equivalent to openMocks(testClass).close()
.
The close method should however only be called after completed usage of testClass
.
If using static-mocks or custom MockMaker
s, using this method might
cause misbehavior of mocks injected into the test class.Mock
, @Spy
, @Captor
, @InjectMocks
See examples in javadoc for MockitoAnnotations
class.