@Documented @Target(value=FIELD) @Retention(value=RUNTIME) public @interface InjectMocks
Currently it only supports setter injection. If you prefer constructor injection - please contribute a patch.
Mockito tries to inject by type (using name in case types are the same). Mockito does not throw anything when injection fails - you will have to satisfy the dependencies manually.
Example:
public class ArticleManagerTest extends SampleBaseTestCase { @Mock private ArticleCalculator calculator; @Mock private ArticleDatabase database; @Spy private UserProvider userProvider = new ConsumerUserProvider(); @InjectMocks private ArticleManager manager = new ArticleManager(); @Test public void shouldDoSomething() { manager.initiateArticle(); verify(database).addListener(any(ArticleListener.class)); } } public class SampleBaseTestCase { @Before public void initMocks() { MockitoAnnotations.initMocks(this); } }The field annotated with @InjectMocks must be initialized.
MockitoAnnotations.injectMocks(this)
method has to called to initialize annotated objects.
In above example, injectMocks()
is called in @Before (JUnit4) method of test's base class.
For JUnit3 injectMocks()
can go to setup()
method of a base class.
You can also put injectMocks() in your JUnit runner (@RunWith) or use built-in runners: MockitoJUnitRunner
Copyright © 2018. All rights reserved.