Best practices for UI testing with Dagger & ViewModels
XabierGoros opened this issue · comments
Currently the UI tests of the project are quite basic or simple and are not mocking behaviors coming from the domain layer. A pretty neat solution for that would be to use the fragment testing AndroidX library with the launchFragmentInContainer
method. Thus, all we have to do is test a single fragment and depending on the different values coming from the viewModel repositories the layout should behave in one way or another. For example, we could UI test the SessionDetailFragment
in isolation mocking it's sessions.
We all know setting up dagger could sometimes be a pain in the ass, and specially this is the case for me. I searched for the best way to mock those viewModels or it's factory and redefine them in the UI tests, but I wasn't able to achieve it in a clean way.
For example, in the GithubBrowserSample project they follow the single activity pattern (which I like) setting a mocked viewModel to the fragment's viewModelFactory
without Dagger. Beforehand, they use a ActivityTestRule
to launch a custom SingleFragmentActivity
with some helpers to replace its fragments. Although it works fine, it would be great to use the latest fragment testing library with dagger.
How could we use the fragment testing library with dagger in this project? I guess the best way is to intercept the dagger injection in the test class and provide custom mocked viewModels there. Thus, we could even mock the viewModel of the very same Activity the Fragment belongs to (e.g: MainActivityViewModel
and it's possible uses in the Activity or Fragments).