Using Robolectric to Test Classes with Dagger-Injected Dependencies in android
It is common for Android code to use dependency injection (DI). And one of the tenets of DI is to make code more testable. So it would follow that if your Android classes use DI, then they should be easily testable. That is true if your class uses constructor injection. You simply call the class’s constructor and provide implementations of its dependencies in the parameters to the constructor. Often, that means passing mocks of the dependencies so you can simulate various conditions in your unit test. But if your class uses field injection, then testing is a little tricker. In that case, you need to construct the object, and then somehow set the values of each injected field before you test any methods that use those fields. The real problem comes when your class uses field injection and you cannot control the creation lifecycle of the class. That is the case with several Android classes, like Activities and Views. The Android framework controls the creation of these. For examp...