使用Mockito自定义应用程序进行Espresso测试

时间:2018-03-19 08:51:52

标签: java android mockito android-espresso ui-testing

这个问题可能微不足道,但我是Android的新手,所以请耐心等待。

我正在尝试使用Mockito和Espresso来测试我的应用程序。我已按照说明herehere创建了MockApplication(扩展了Application),MockApplicationComponent和MockApplicationModule。

在我的测试类中,我尝试像这样设置应用程序....

@Rule
public ActivityTestRule<OnboardActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

@Before
public void setup() {

    Application app = mActivityTestRule.getActivity().getApplication();
    TestApplication testApp;

    if (!(app instanceof TestApplication)) {
        throw new RuntimeException("Failed to downcast "+app.getClass().toString());
    }
    testApp = (TestApplication) app;

    MockApplicationModule module  = new MockApplicationModule(testApp);
    .......
    .......
}

这是TestApplication

public class TestApplication extends Application {
private ApplicationModule applicationModule;

@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
}

@Override
ApplicationModule getApplicationModule() {
    return new MockApplicationModule(this);
}

@Override
protected void attachBaseContext(Context base) {
    try {
        super.attachBaseContext(base);
    } catch (RuntimeException ignored) {
        // Multidex support doesn't play well with Robolectric yet
    }
}

// We store an instance of application module because we want to be able to
// override in our test setup later
public void setApplicationModule(ApplicationModule mApplicationModule) {
    this.applicationModule = mApplicationModule;
    initComponent();
}

@Override
protected void initComponent() {
    component = DaggerApplicationComponent.builder()
            .applicationModule(getApplicationModule())
            .build();
}}

显然,我在测试类中不正确地向下转换,并且总是收到运行时异常。

让Activity使用TestApplication而不是应用程序的最佳方法是什么?

谢谢。

0 个答案:

没有答案