0

This answer has been very helpful in pointing me in the right direction.

However, things are not entirely clear to me.

Please, can somebody explain me a bit better:

  • Option 1: Override bindings by subclassing modules

That would mean that I actually will have to change the production code so that I can inject the mock dependency?

Example:

@Test
public void testFoo(){
MyClass class=new MyClass();
assertTrue(class.doStuff());
}

public class MyClass(){
@Inject
private Dependency dependency;

public MyClass(){}   
MyDaggerComponent.builder().foo(new MockDependency).build.inject(MyClass.this);
}

This would mean that I would need to change MyClass to pass the mock module,

correct?

  • Option 2: Separate component configurations

Would that mean that I would have 2 Gradle productFlavors, - one containing the production Module and Component, - one containing the mocks.

correct?


Thanks for your help!

Community
  • 1
  • 1
Lisa Anne
  • 4,482
  • 17
  • 83
  • 157

1 Answers1

0

The power of dependency injection comes really handy especially for testing since you can easily switch your dependencies in the test environment to dummy dependencies.

The way it should be built is like the following:

  • The dependecies in your production code should be injected not hard coded.
  • In your test environment you should build the equivalent test modules and test components that will replace what ever dependencies you have in your actual code.

If you want a proper example I would really suggest you to check this boilerplate since it is fully based on DI using Dagger2.

The dependencies currently handled by the boiler plate are the following:

  • Database dependency: encapsulates all the database operations.
  • Shared preferences dependency: deals with shared preferences.
  • Local files dependency: which deals with saving on files.
  • Analytics dependency: covers all the operation of reporting events to your analytics backend (GA, Segment, FB, Flurry ..)
  • Logging dependency: encapsulates all the operations related to logging to your console
  • Api dependency: encapsulates all the API related operations
Abed Almoradi
  • 131
  • 1
  • 2