我正在尝试使用Mockito和Dagger测试一个Activity。 我已经能够在我的应用程序中将依赖项注入到Activity中,但是当测试该Activity时,我无法将Mock注入到Activity中。 我应该将Activity注入进行测试,还是让getActivity()创建它?
我试图使用Mockito和Dagger来测试一个Activity。我已经成功地将依赖项注入到应用程序的Activity中,但是在测试Activity时,我无法注入mock对象。我不确定是将Activity注入到测试中,还是让getActivity()方法创建它。请问应该如何处理?
public class MainActivityTest extends
ActivityInstrumentationTestCase2<MainActivity> {
@Inject Engine engineMock;
private MainActivity mActivity;
private Button mLogoutBtn;
public MainActivityTest() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
// Inject engineMock to test
ObjectGraph.create(new TestModule()).inject(this);
}
@Override
protected void tearDown() {
if (mActivity != null)
mActivity.finish();
}
@Module(
includes = MainModule.class,
entryPoints = MainActivityTest.class,
overrides = true
)
static class TestModule {
@Provides
@Singleton
Engine provideEngine() {
return mock(Engine.class);
}
}
@UiThreadTest
public void testLogoutButton() {
when(engineMock.isLoggedIn()).thenReturn(true);
mActivity = getActivity();
mLogoutBtn = (Button) mActivity.findViewById(R.id.logoutButton);
// how to inject engineMock to Activity under test?
ObjectGraph.create(new TestModule()).inject(this.mActivity);
assertTrue(mLogoutBtn.isEnabled() == true);
}
}