Skip to content

Instantly share code, notes, and snippets.

@vaughandroid
Last active April 26, 2018 14:46
Show Gist options
  • Save vaughandroid/9aae0dd45469d088ff37cfea5072b999 to your computer and use it in GitHub Desktop.
Save vaughandroid/9aae0dd45469d088ff37cfea5072b999 to your computer and use it in GitHub Desktop.
Demonstration of Dagger 2 per-test Activity injection (if https://github.com/google/dagger/issues/648 is resolved)
@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 {
// Mock the injector and set it in the App.
myApp.dispatchingAndroidInjector = new Injector();
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);
}
// Can't actually do this since DispatchingAndroidInjector isn't mockable (yet).
public static class Injector implements DispatchingAndroidInjector<MyActivity> {
@Override
public void inject(MyActivity instance) {
instance.singletonString = "test-singleton-value";
instance.perActivityString = "test-per-activity-value";
}
}
}
@SanjayMallur
Copy link

@vaughandroid is "DispatchingAndroidInjector" is still not mockable..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment