2015-03-03 30 views
2

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

我想写一个使用espresso的测试套件。我想使用自定义注入模块,所以我可以使用Mockito来嘲笑Retrofit的响应。

如何更改我的测试套件以使用Roboguice中保留浓缩咖啡的自定义注射模块。 PS:我已经看到了如何与Roboelectric做到这一点,但我现在不使用Roboelectric。

+0

你有没有得到一个解决方案? – emaillenin 2015-07-26 12:48:32

回答

2

我偶然发现了同样的问题,我无法找到这个在线的简单解决方案。经过一天的尝试并失败后,我终于找到了适合我的解决方案。

您需要声明一个自定义的ActivityTestRule类,以在活动启动之前覆盖应用程序注入器。这里是一个例子:

@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("", ""); 
    } 

    // ... 
} 

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