【问题标题】:Change injection modules for Espresso更改 Espresso 的注入模块
【发布时间】:2015-05-03 22:22:01
【问题描述】:

我有一个应用程序可以调用 REST API。 我正在使用 Retrofit 来实现 API,我正在使用 Roboguice 在需要的地方注入我的 REST 服务。

我正在尝试使用 espresso 编写一个测试套件。我想使用自定义注入模块,这样我就可以使用 Mockito 模拟 Retrofit 的响应。

如何更改我的测试套件以使用来自 Roboguice 的自定义注入模块来保持 espresso。

PS:我已经了解如何使用 Roboelectric 做到这一点,但我现在没有使用 Roboelectric。

【问题讨论】:

  • 您找到解决方案了吗?

标签: android roboguice android-espresso


【解决方案1】:

根据https://github.com/roboguice/roboguice/wiki/Your-First-Testcase,您应该调用RoboGuice.util.reset() 来拆除自定义注入器。你可以放它

        @Override
        protected void afterActivityFinished() {
            RoboGuice.util.reset();
        }

【讨论】:

    【解决方案2】:

    我偶然发现了同样的问题,但我在网上找不到简单的解决方案。经过一天的尝试和失败,我终于找到了适合我的解决方案。

    您需要在 Activity 启动之前声明一个自定义的 ActivityTestRule 类来覆盖 Application Injector。这是一个例子:

    @RunWith(AndroidJUnit4.class)
    public class LoginActivityTest {
    
        protected final Api mApi = mock(Api.class);
        // declare the other mocks you want here
        protected final AbstractModule mTestModule = new MyTestModule();
    
        @Rule
        public ActivityTestRule<LoginActivity> mActivityRule = new RoboGuiceActivityTestRule<>(LoginActivity.class);
    
        private class RoboGuiceActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
    
            public RoboGuiceActivityTestRule(Class<T> activityClass) {
                super(activityClass);
            }
    
            @Override
            protected void beforeActivityLaunched() {
                RoboGuice.overrideApplicationInjector((Application) InstrumentationRegistry.getTargetContext().getApplicationContext(), mTestModule);
            }
        }
    
        private class MyTestModule extends AbstractModule {
    
            @Override
            protected void configure() {
                bind(Api.class).toInstance(mApi);
                // bind the other mocks here
            }
        }
    
        @Test
        public void checkEmptyFormDoNotPerformLogin() throws Exception {
            onView(withId(R.id.etLogin)).perform(clearText());
            onView(withId(R.id.etPassword)).perform(clearText());
            onView(withId(R.id.btLogin)).perform(click());
            verify(mApi, times(0)).login("", "");
        }
    
        // ...
    }
    

    当然,您可以提取类并将模块传递给构造函数以获得更简洁的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2023-03-14
      • 2016-09-24
      相关资源
      最近更新 更多