Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating test dependencies when using Dagger2

While reading the docs for dagger 2 I cannot find an easy way to provide a dependency when building an app for testing. The only clue I've found is this:

Dagger 2 doesn't support overrides. Modules that override for simple testing fakes can create a subclass of the module to emulate that behaviour. Modules that use overrides and rely on dependency injection should be decomposed so that the overridden modules are instead represented as a choice between two modules.

I don't understand how I would set up such a configuration on Android, anyone can explain?

like image 498
Julian Suarez Avatar asked Apr 30 '15 14:04

Julian Suarez


People also ask

Is dependency injection good for testing?

Using dependency injection can be great for simplifying your code and keeping it DRY, it can also simplify testing and even improve testability.

What is Dagger2 and why do you use it?

Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.

How is dependency injection used in testing?

Dependency injection allows unit testing, but it also allow modification of an object's behavior without altering the code of that object (open/closed principle). So, it isn't just testable code, but flexible code that results.


1 Answers

This is currently impossible with Dagger 2 (as of v2.0.0) without some workarounds. You can read about it here.

I've proposed one workaround but this requires changes to the production code.

In short:

  • provide additional setter for @Component (e.g. in Android setter in Application class)
  • test component must extend the production component

For more information please check both links. Hope this issue will be addressed in future versions of Dagger 2.

like image 149
tomrozb Avatar answered Oct 06 '22 18:10

tomrozb