Skip to content

Instantly share code, notes, and snippets.

@vaughandroid
Created March 24, 2017 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaughandroid/3c3c260fc7fcb64a628a55712a87736c to your computer and use it in GitHub Desktop.
Save vaughandroid/3c3c260fc7fcb64a628a55712a87736c to your computer and use it in GitHub Desktop.
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