我正在使用Robolectric运行JUnit测试。我正在尝试测试注入成员的Activity。我能够让我的测试类正确地注入自己的成员。但仍然不能将嘲笑注入我的活动成员。
我试过
@Inject LoginActivity loginActivity;
也试过
LoginActivity activity = new LoginActivity();
injector.injectMembers(activity);
我的测试
@RunWith(RobolectricTestRunner.class)
public class LoginActivityTest {
protected Injector injector;
// This get injected correctly
@Inject
protected IServiceClient serviceClient;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, new MobileTestModule());
injector = RoboGuice.getBaseApplicationInjector(Robolectric.application);
injector.injectMembers(this);
LoginActivity activity = new LoginActivity();
// This fails
injector.injectMembers(activity);
}
@After
public void tearDown() {
}
我的DI模块
public class MobileTestModule extends AbstractModule {
@Override
protected void configure() {
// Services
bind(IServiceClient.class).toInstance(Mockito.mock(IServiceClient.class));
// Other binding here
}
}
修改
这是我正在获得的例外
com.google.inject.ConfigurationException: Guice configuration errors:
1) No implementation for android.content.Context was bound.
while locating android.content.Context
for parameter 0 at com.company.app.helpers.SlideMenuAdapter.<init>(Unknown Source)
while locating com.company.app.helpers.SlideMenuAdapter
for field atcompanycom.company.atlasmobile.helpers.AtlasPhoneActivity.slideMenuAdapter(Unknown Source)
while locating com.company.app.pages.login.LoginActivity
for field at com.company.app.test.LoginActivityTest.loginActivity(Unknown Source)
while locating com.company.app.test.LoginActivityTest
2) No scope is bound to roboguice.inject.ContextSingleton.
at roboguice.inject.ContentViewListener.class(Unknown Source)
while locating roboguice.inject.ContentViewListener
for field at roboguice.activity.RoboActivity.ignored(Unknown Source)
while locating com.nuvasive.atlasmobile.pages.login.LoginActivity
for field at com.nuvasive.atlasmobile.test.LoginActivityTest.loginActivity(Unknown Source)
while locating com.company.app.test.LoginActivityTest
答案 0 :(得分:0)
以下是如何使用Robolectric设置RoboGuice,并强制注入测试类成员。
// Setup Module
RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, Modules.override(RoboGuice.newDefaultRoboModule(Robolectric.application)).with(new MyModule()));
// Get an Injector instance
injector = RoboGuice.getInjector(Robolectric.application);
// Inject properties on test class members (Marked with @Inject)
injector.injectMembers(this);
以下是使用Robolectric时初始化活动的方法
LoginActivity activity = Robolectric.buildActivity(LoginActivity.class).create().get();