I have an activity with a dependency:
public class MyActivity extends AppCompatActivity {
@Inject Dependency;
@Override
protected void onCreate(Bundle savedInstanceState) {
// inject
}
}
public class Dependency {
@Inject
public Dependency() {
//..
}
}
Since Dependency has an injected constructor, Dagger2 doesn't require a module to know how to instantiate it, which is super convenient.
My question is: For testing purposes, do I have to have an explicit module that provides Dependency in order to be able to mock it and provide a mock version of Dependency? or is there a way to mock Dependency without it?
I found a way without creating an explicit Module. Here's how I did it using Robolectric and Mockito:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MyActivityTest {
@Mock AppComponent mAppComponent;
@Mock private Dependency mDependency;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
// ***
// use the mock AppComponent to perform injections
// ***
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
((MyActivity) invocation.getArguments()[0]).mDependecy = mDependecy;
return null;
}
}).when(mAppComponent).inject(any(MyActivity.class));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With