我正在尝试使用 Mockito & Dagger测试 Activity 。我已经能够在我的应用程序中向 Activity 注入依赖项,但是在测试 Activity 时,我无法向 Activity 注入模拟。我应该注入 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);
}
}