Analog injection constructor in dagger 2
•
Android
I have a dependent activity:
public class MyActivity extends AppCompatActivity {
@Inject Dependency;
@Override
protected void onCreate(Bundle savedInstanceState) {
// inject
}
}
public class Dependency {
@Inject
public Dependency() {
//..
}
}
Because dependency has an injected constructor, dagger2 does not need the module to know how to instantiate it, which is very convenient
My question is: in order to test, do I have to have an explicit module that provides dependencies so that I can simulate it and provide a simulated dependency version? Or is there a way to simulate dependencies?
resolvent:
I found a way without creating explicit modules. This is what I did with 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));
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码