Last active
April 26, 2018 14:46
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vaughandroid is "DispatchingAndroidInjector" is still not mockable..?