在InstrumentationTestCase运行之间重置应用程序状态 [英] Reset app state between InstrumentationTestCase runs

查看:71
本文介绍了在InstrumentationTestCase运行之间重置应用程序状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一名质量检查工程师正在支持具有相当大的代码库和许多不同的SharedPreferences文件的应用程序.几天前,他来找我,询问如何在两次测试运行之间重置应用程序状态,就像已将其卸载后重新安装一样.

One of my QA engineers is supporting an app with a fairly large codebase and a lot of different SharedPreferences files. He came to me the other day asking how to reset the application state between test runs, as if it had been uninstalled-reinstalled.

看起来Espresso(他正在使用)或Android测试框架本身都不支持它,所以我不确定该告诉他什么.使用本机方法清除所有不同的SharedPreferences文件将是一个非常脆弱的解决方案.

It doesn't look like that's supported by Espresso (which he is using) nor by the Android test framework natively, so I'm not sure what to tell him. Having a native method to clear all the different SharedPreferences files would be a pretty brittle solution.

如何在检测过程中重置应用程序状态?

How can one reset the application state during instrumentation?

推荐答案

当前的espresso不提供任何重置应用程序状态的机制.但是对于每个方面(首选项,数据库,文件,权限)都存在一个解决方案.

Current espresso doesn't provide any mechanism to reset application state. But for each aspect (pref, db, files, permissions) exist a solution.

最初,您必须避免浓缩咖啡自动开始您的活动,以便您有足够的时间进行重置.

Initial you must avoid that espresso starts your activity automatically so you have enough time to reset.

@Rule
public ActivityTestRule<Activity> activityTestRule = new ActivityTestRule<>(Activity.class, false, false);

然后通过

activityTestRule.launchActivity(null)

要重置首选项,您可以使用以下代码段(在开始活动之前)

For reseting preferences you can use following snippet (before starting your activity)

File root = InstrumentationRegistry.getTargetContext().getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
    InstrumentationRegistry.getTargetContext().getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}

您也可以在开始活动后重设首选项.但随后该活动可能已经阅读了首选项.

You can reset preferences after starting your activity too. But then the activity may have already read the preferences.

您的应用程序类仅启动一次,并且已经启动,您可以重置首选项.

Your application class is only started once and already started before you can reset preferences.

我已经开始编写一个库,该库应该使使用espresso和uiautomator的测试更加简单.这包括用于重置应用程序数据的工具. https://github.com/nenick/espresso-macchiato 例如,请参见EspAppDataTool及其方法清除首选项,数据库,缓存的文件和存储的文件.

I have started to write an library which should make testing more simple with espresso and uiautomator. This includes tooling for reseting application data. https://github.com/nenick/espresso-macchiato See for example EspAppDataTool with the methods for clearing preferences, databases, cached files and stored files.

这篇关于在InstrumentationTestCase运行之间重置应用程序状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆