Skip to content

Instantly share code, notes, and snippets.

@Sloy
Last active June 7, 2018 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sloy/c45dc3291403e603b4b88755e4a67660 to your computer and use it in GitHub Desktop.
Save Sloy/c45dc3291403e603b4b88755e4a67660 to your computer and use it in GitHub Desktop.
Injector (Dagger 1)
public class InjectedInstrumentationTestRule implements MethodRule {
private final Object testModule;
public InjectedInstrumentationTestRule(Object testModule) {
this.testModule = testModule;
}
@Override
public Statement apply(final Statement statement, FrameworkMethod frameworkMethod, final Object testClassInstance) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
setUpInjection(testClassInstance);
statement.evaluate();
tearDownInjection();
}
};
}
private void setUpInjection(Object testClass) {
Application application = getApplication();
List<Object> testModules = new LinkedList<>();
testModules.addAll(Injector.getModules(application));
testModules.add(testModule);
ObjectGraph testObjectGraph = ObjectGraph.create(testModules.toArray());
Injector.replaceGraph(testObjectGraph);
testObjectGraph.inject(testClass);
}
private void tearDownInjection() throws Exception {
Injector.resetFakeGraph();
}
private Application getApplication() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
return (Application) instrumentation.getTargetContext().getApplicationContext();
}
}
public class Injector {
private static ObjectGraph objectGraph;
private static ObjectGraph fakeObjectGraph;
public static void inject(Object target) {
getCurrentGraph().inject(target);
}
public static void inject(Context target) {
getCurrentGraph().inject(target);
}
public static void init(Application application) {
objectGraph = ObjectGraph.create(getModules(application).toArray());
objectGraph.injectStatics();
}
@VisibleForTesting
public static void replaceGraph(ObjectGraph newObjectGraph) {
fakeObjectGraph = newObjectGraph;
}
@VisibleForTesting
public static void resetFakeGraph() {
fakeObjectGraph = null;
}
@VisibleForTesting
public static List<Object> getModules(Application application) {
List<Object> modules = new LinkedList<>();
modules.addAll(MainModulesFactory.get(application));
modules.addAll(BuildTypeModulesFactory.get());
return modules;
}
private static ObjectGraph getCurrentGraph() {
return fakeObjectGraph == null
? objectGraph
: fakeObjectGraph;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment