我在Android Studio中使用espresso编写测试。现在有很多测试,在我运行之前,我必须删除应用程序的缓存。我尝试了很多我知道的选择,但都没有成功。我在网站上搜索了这个问题,并尝试了一下结果,但都不起作用。
例如,应用程序中有一个阶段会导致性别寻址的变化(我的应用程序是外语的(,我在本节中测试了很多东西,我从3个不同的测试用户登录,每个用户都有一个不同的视图,除非删除缓存,否则无法更改。如果不删除缓存,我无法将它们一起运行,但我可以分别运行它们中的每一个。该应用程序在用户登录的momnet中定义自己,因此为了切换用户,我需要删除应用程序缓存。
我在这里附上了一些链接,介绍了我尝试过的、本应有效但没有成功的方法。他们可能能够帮助和解释
在测试案例浓缩咖啡之前清除数据库
在InstrumentationTestCase运行之间重置应用程序状态
https://github.com/chiuki/espresso-samples/issues/3
https://discuss.appium.io/t/android-how-to-clear-app-data-before-test/7166/10
每个测试类清除数据库一次
将以下代码添加到您的Android测试类:
companion object {
@BeforeClass
fun clearDatabase() {
InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("pm clear PACKAGE_NAME").close()
}
}
每次测试前清除数据库
在每次测试运行之前清除数据库的另一种方法是在使用Android test Orchestrator时设置clearPackageData标志。这将";在每次测试后从设备的CPU和存储器中删除所有共享状态:;
将以下语句添加到项目的build.gradle文件中:
android { defaultConfig { ... testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" // The following argument makes the Android Test Orchestrator run its // "pm clear" command after each test invocation. This command ensures // that the app's state is completely cleared between tests. testInstrumentationRunnerArguments clearPackageData: 'true' } testOptions { execution 'ANDROIDX_TEST_ORCHESTRATOR' } } dependencies { androidTestImplementation 'androidx.test:runner:1.1.0' androidTestUtil 'androidx.test:orchestrator:1.1.0' }
对我来说,我添加了BuildConfig
来为您查找包(万一您稍后更改(
@Before
fun setup() {
InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("pm clear ${BuildConfig.APPLICATION_ID}").close()
}
第二种方法是很容易地在构建渐变中添加一行
android {
defaultConfig {
...
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// The following argument makes the Android Test Orchestrator run its
// "pm clear" command after each test invocation. This command ensures
// that the app's state is completely cleared between tests.
testInstrumentationRunnerArguments clearPackageData: 'true'
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestUtil 'androidx.test:orchestrator:1.1.0'
}
指:https://developer.android.com/training/testing/instrumented-tests/androidx-test-libraries/runner#enable-渐变
Kotlin
@Test
fun clearStorage() {
InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("pm clear PACKAGE NAME").close()
}