All posts
Android, Blog

Testing Dagger 2 with Espresso, Mockito & Robolectric

Paulina Szklarska

Paulina Szklarska

Dagger 2 brings us @Component and @Module – annotations which imply less boilerplate code, but unfortunately, make our project less testable. In this article, I will show a project, which is using Dagger 2 and is testable with frameworks like Mockito, Espresso or Robolectric.

Anyone who has ever tried testing an Android project that is using Dagger 1 knows, that this is quite possible to override existing modules and replace them with test ones, e.g.:

Dagger 2 brings us @Component and @Module, annotations which imply less boilerplate code, but unfortunately, makes our project less testable. In this article, I’d like to show the project which is using Dagger 2 and is testable with frameworks like Mockito, Espresso or Robolectric.


Complete source code can be found on Droids On Roids Github

Making project

Newsletter

The post is created by Droids On Roids Team Member.
We would love to take care of your business.

Leave comment

  • Hai Nguyen

    Great article,

    Is there any way we can inject the presenter in the test classes i.e. instead of mocking the presenter, we inject it using Dagger 2? We were able to do that with Dagger 1

    Thanks

    • Paulina Szklarska

      Hi Hai,

      thank you for your comment. It’s possible to inject the presenter (or any other class) to test classes, you can see how it can be done on repository branch dev.

      Anyway, there’s no need for doing this if you want only to inject presenter. The method presented in article also injects presenter (using MainActivity class), but for doing this it uses modules from test package. TestMainModule tells Dagger that you want to use mocked Presenter. But if you change this override, you can tell Dagger to use original presenter from MainModule.

      I hope I explained this a bit more. If you have any questions, feel free to comment.
      Thanks,
      Paulina Szklarska

  • Federico Paolinelli

    Hi, nice article. Given that you are using Robolectric, you could take advantage of the fact that it allows to use a different Application object, getting rid of the isTesting boolean in your production code and allowing a different Application object to inject mocks..