Last active
March 11, 2020 20:50
-
-
Save vaughandroid/00287633102af6a66dc8 to your computer and use it in GitHub Desktop.
Overriding Dagger 2 Modules in the simplest way I know how
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
@Component(modules=MyModule.class) | |
@ApplicationScope | |
public interface MyComponent { | |
void inject(MyApplication application); | |
} | |
@Module | |
public class MyModule { | |
@Provides @ApplicationScope | |
public String provideString() { | |
return "real string"; | |
} | |
} | |
public class MyApplication extends Application { | |
@Inject public String injectedString; | |
private MyComponent component; | |
public void setComponent(MyComponent component) { | |
this.component = component; | |
component.inject(this); | |
Log.d("Injected: " + injectedString); | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
if (component == null) { | |
setComponent(DaggerMyComponent.create()); | |
} | |
} | |
} | |
public class MyActivityTest { | |
MyApplication app; | |
@Before | |
public void setUp() { | |
app = (MyApplication) getInstrumentation().getTargetContext().getApplicationContext(); | |
// This is the sneaky bit. Create a partial mock of the Module you want to override, | |
// then just mock the provider methods you want to override. | |
MyModule module = new MyModule()); | |
Mockito.doReturn("mocked string").when(module).provideString(); | |
MyComponent component = DaggerMyComponent.builder() | |
.myModule(new MyModule() { | |
// Note: Do NOT add @Provides or @ApplicationScope or Dagger 2 will throw an error at compile time. | |
@Override | |
public String provideString() { | |
return "mocked string"; | |
} | |
}) | |
.build(); | |
app.setComponent(component); | |
} | |
@Test | |
public void mock_injected_successfully() { | |
assertEquals("mocked string", app.injectedString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 44 looks incomplete