I have a heavily dependency injected (dagger2) application. I would like to run an espresso test without having the test navigate through the whole application, and log into the application.
I would like to start on my teleActivity, and mock the login manager. However in any @test function, we have already hit the null pointer as we have called onCreate. If I override it before we launch the activity (show below) the activity is null.
To my understanding, the ability to switch our underlining dependencies is a large reason why we use Dagger2, else it would be just a very over engineered singleton. How do I override, mock, or switch the injection to a testing dagger module -- so I can create this simple espresso test.
Note I also wrote all this in the MVP design pattern if that makes a difference.
TeleActivity
@Inject
TelePresenter mTelePresenter;
@Inject
public LoginStateManager mLoginStateManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
DaggerInjectorTele.get().inject(this);
mTelePresenter.setTeleDependencies(this);
Intent intent = getIntent();
String searchId = null;
if (intent != null) {
searchId = intent.getStringExtra(Constants.SEARCH_ID);
}
mTelePresenter.onCreateEvent(searchId,
Helper.makeAuthorizationHeader(
// CRASH Null pointer
mLoginStateManager.getBaseLoginResponse().getAccessToken()));
}
Espresso
@LargeTest
@RunWith(AndroidJUnit4.class)
public class TeleTest {
@Rule
public ActivityTestRule<TeleActivity> mActivityTestRule = new ActivityTestRule(
TeleActivity.class) {
@Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
TeleActivity teleActivity = (TeleActivity)getActivity();
//teleActivity NULL!
teleActivity.mLoginStateManager = mock(LoginStateManager.class);
LoginResponse loginResponse = mock(LoginResponse.class);
when(loginResponse.getAccessToken()).thenReturn("1234");
// Nope here still null
when(teleActivity.mLoginStateManager.getBaseLoginResponse()).thenReturn(loginResponse);
}
};
Dagger Injector
public class DaggerInjectorTele {
private static TelePresenterComponent telePresenterComponent =
DaggerTelePresenterComponent.builder().build();
public static TelePresenterComponent get() {
return telePresenterComponent;
}
}
TelePresenterComponent
@Singleton
@Component(modules = {TelePresenterModule.class,
LoginStateManagerModule.class})
public interface TelePresenterComponent {
void inject(TeleActivity activity);
}
TelePresenterModule
@Module
public class TelePresenterModule {
@Provides
@Singleton
public TelePresenter getTelePresenter() {
return new TelePresenter();
}
}
LoginStateManagerModule
@Module
public class LoginStateManagerModule {
@Provides
@Singleton
public LoginStateManager getLoginStateManager(){
return new LoginStateManager();
}
}