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

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

问题描述

我的一位 QA 工程师正在为一个应用程序提供相当大的代码库和许多不同的 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天全站免登陆