Skip to content

Instantly share code, notes, and snippets.

Created March 24, 2017 17:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Demonstration of Dagger 2 per-test Activity injection
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.
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);
public static class TestAppModule {
@Provides @IntoMap @ActivityKey(MyActivity.class)
AndroidInjector.Factory<? extends Activity> factory() {
return new AndroidInjector.Factory<MyActivity>() {
public AndroidInjector<MyActivity> create(MyActivity instance) {
return new AndroidInjector<MyActivity>() {
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