Create a gist now

Instantly share code, notes, and snippets.

Embed
Demonstration of Dagger 2 per-test Activity injection
@RunWith(AndroidJUnit4.class)
public class MyActivityTest {
@Rule public ActivityTestRule<MyActivity> activityTestRule = new ActivityTestRule<>(MyActivity.class, false, false);
private MyApp myApp;
@Before public void setup() {
myApp = (MyApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
}
@Test public void mockInjection() throws Exception {
// Create test object graph & inject.
DaggerMyActivityTest_TestAppComponent.builder()
.build()
.inject(myApp);
activityTestRule.launchActivity(new Intent(myApp, MyActivity.class));
MyActivity myActivity = activityTestRule.getActivity();
// Check things got injected correctly.
Assert.assertEquals("test-singleton-value", myActivity.singletonString);
Assert.assertEquals("test-per-activity-value", myActivity.perActivityString);
}
@Singleton @Component(modules = { TestAppModule.class, AndroidInjectionModule.class })
public interface TestAppComponent {
void inject(MyApp myApp);
}
@Module
public static class TestAppModule {
@Provides @IntoMap @ActivityKey(MyActivity.class)
AndroidInjector.Factory<? extends Activity> factory() {
return new AndroidInjector.Factory<MyActivity>() {
@Override
public AndroidInjector<MyActivity> create(MyActivity instance) {
return new AndroidInjector<MyActivity>() {
@Override
public void inject(MyActivity instance) {
instance.singletonString = "test-singleton-value";
instance.perActivityString = "test-per-activity-value";
}
};
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment