1

I am using very simple and likely very common scenario. Here is my sample dependency:

public class MyDependency {
   @Inject
   public MyDependency(...) {
      ...
   }
}

I am not listing the above in any module (that is, there is no @Provides for MyDependency).

My sample use case goes like this:

public class ThePresenter {
   @Inject
   MyDependency myDependency;

   public ThePresenter() {
      App.getInstance().getAppComponent().inject(this);
   }
}

Now I'd like to mock my dependency in unit tests. I don't want to use modules overrides (that would mean I have to add @Provides for all my dependencies marked with @Inject constructors), test components etc. Is there any alternative but standard and simple approach for the problem?

ror
  • 3,295
  • 1
  • 19
  • 27

2 Answers2

0

Just mock it?

public class ThePresenterTest {

   @Mock MyDependency myDependency;

   private ThePresenter presenter;

   @Before
   public void setup() {
      initMocks(this);
      presenter = new ThePresenter();
   }
}
JakeB
  • 2,043
  • 3
  • 12
  • 19
0

You need to use constructor injection, rather than your injection site inside the Presenter class constructor. Expose your Presenter to dagger2 by adding the @Inject annotation on the constructor (like you have done with the dependency):

public class ThePresenter {

   private final MyDependency myDependency;

   @Inject public ThePresenter(MyDependency myDependency) {
      this.myDependency = myDependency;
   }
}

This then allows inversion of control and supplying the dependency/mock.

Usage :

public class ThePresenterTest {

   @Mock private MyDependency myDependency;

   private ThePresenter presenter;

   @Before public void setup() {
      MocktioAnnotations.initMocks(this);
      presenter = new ThePresenter(myDependency);

      Mockito.when(myDependency.someMethod()).thenReturn(someValue);
      ....
   }
}
Mark
  • 9,604
  • 5
  • 36
  • 64
  • Strictly speaking this does not solve my problem as presenter is instantiated by the framework https://github.com/konmik/nucleus thus I cannot do normal constructor injection, but imo what you propose is the only viable solution if framework part is not taken into consideration. I think Dagger is overhyped in more then a few edge cases! – ror Sep 09 '19 at 07:43
  • Ok I didn't understand you were using a library. As regards to dagger, life is made easier if you have full control of the dependency graph, and how dependencies are supplied. As for dagger overhyped, as soon as you require scoped dependencies or your project becomes large then the benefits of dagger become far more apparent. Generally small projects are candidates for not using dependency injection libraries. – Mark Sep 09 '19 at 09:51