1

I am attempting to use Mockito to unit test an Android application, specifically a fragment that gets initialized use newInstance(). I am having trouble injecting my Mock object into a private member variable of the object under test. All the examples I have seen show using new() instead of newInstance() and also show the @InjectMocks annotation on the same line as the initialization. Can I not declare the variable with the annotation but wait to initialize it later?

I have:

public class  MyFragmentTest extends TestCase {
    @Mock (name="memberVariableName") private MyObject mMyObjectMock;
    @InjectMocks private MyFragment mFragment;

    @Override
    protected void setUp() throws Exception {
       super.setUp();
       // Initialize mock objects that are being injected
       MockitoAnnotations.initMocks(this);

       // Work around for a known issue with Mockito and Dexmaker
       System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().getPath());
    }
}
tjpaul
  • 343
  • 3
  • 16
  • 2
    The javadoc of [`@InjectMocks`](http://site.mockito.org/mockito/docs/current/org/mockito/InjectMocks.html) is pretty well documented as how mockito will perform the injection, if `MyFragment` has a no-arg constructor then setter or field injection will be used. But if the constructor takes args, then **all** args have to be present as `@Mock` fields in the test class. – bric3 Feb 14 '15 at 11:16
  • On a side note I would recommend to use JUnit 4 and the annotations ([now possible](http://stackoverflow.com/questions/9809180/why-is-junit-4-on-android-not-working)) and use the [mockito rule (_use 1.10.19_)](http://site.mockito.org/mockito/docs/current/org/mockito/junit/MockitoJUnit.html) `@Rule MockitoRule mockitoRule = MockitoJUnit.rule();` instead of `initMocks(this)`, it does more things than just initializing mocks. – bric3 Feb 14 '15 at 11:18

0 Answers0