Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger2 - Injection of replacement modules without duplicating code

Tags:

java

dagger-2

I have this setup of component plus module, say FooComponent and FooModule, which provides a simple singleton, which needs to be replaced in one of the test variants. Therefore, in the variant I have instead FooTestComponent, which inherits FooComponent, but its @Modules annotation points to another module instead, FooTestModule. So far FooModule provides only one dependency, so no problem with that.

However, as dependencies that need not to be replaced in tests are added to FooModule, I see myself forced to replicate all of the methods to provide them in FooTestModule too since they can't be extracted to a parent abstract module that both FooModule and FooTestModule inherit from. What is the way to avoid this duplication?

like image 560
Jorge Antonio Díaz-Benito Avatar asked Aug 10 '26 03:08

Jorge Antonio Díaz-Benito


1 Answers

The Dagger 2 User's Guide Testing Section contains advice for this very scenario.

To summarize the advice there:

  1. Subclassing modules in order to swap in test doubles leads to the situation where you have to resolve all of the dependencies even if they are unused. Don't do this!
  2. Instead of the approach in point 1, use different component configurations to achieve this: you can have a TestComponent that extends ProductionComponent and uses different modules that include bindings for test doubles
  3. To achieve point 2, organize your modules for testability. This means considering modules as a collection of published and internal bindings and making sure you have a separate module for each published binding that has a 'reasonable alternative' i.e., an alternative you might like to replace with a test double that is not a mere internal dependency.
like image 181
David Rawson Avatar answered Aug 13 '26 04:08

David Rawson