Skip to content

Instantly share code, notes, and snippets.

@ralphpina
Created February 14, 2017 06:44
Show Gist options
  • Save ralphpina/e7d4bd25f1e172d9569963f5631c06c0 to your computer and use it in GitHub Desktop.
Save ralphpina/e7d4bd25f1e172d9569963f5631c06c0 to your computer and use it in GitHub Desktop.
test rule
public class TestComponentRule implements TestRule {
private ApplicationTestModule module;
private TestComponent testComponent;
private TestComponentRule(ApplicationTestModule applicationTestModule) {
this.module = applicationTestModule;
}
private void setupDaggerTestComponentInApplication() {
App application = App.get();
if (application == null) { // this will be null in Unit Tests
application = new App();
}
// this needs to be set here, because during the builder process
// the Application has not been instantiated.
module.setApplication(application);
testComponent = DaggerTestComponent.builder()
.applicationTestModule(module)
.build();
application.setComponent(testComponent);
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
setupDaggerTestComponentInApplication();
base.evaluate();
} finally {
testComponent = null;
}
}
};
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment