如何检测Android应用程序是否正在使用Espresso运行UI测试 [英] How to detect whether android app is running UI test with Espresso
问题描述
我正在为Android编写一些Espresso测试.我正在运行以下问题:
I am writing some Espresso tests for Android. I am running in the the following problem:
为了使某些测试用例正常运行,我需要禁用应用程序中的某些功能.因此,在我的应用中,我需要检测我是否正在运行Espresso测试,以便可以将其禁用.但是,我不想使用BuildConfig.DEBUG
,因为我不想在调试版本中禁用这些功能.另外,我想避免创建新的buildConfig,以免创建太多的构建变体(我们已经定义了很多样式).
In order for a certain test case to run properly, I need to disable some features in the app. Therefore, in my app, I need to detect whether I am running Espresso test so that I can disable it. However, I don't want to use BuildConfig.DEBUG
to because I don't want those features to be disabled in a debug build. Also, I would like to avoid creating a new buildConfig to avoid too many build variants to be created (we already have a lot of flavors defined).
我一直在寻找一种定义buildConfigField进行测试的方法,但是我在Google上找不到任何引用.
I was looking for a way to define buildConfigField for test but I couldn't find any reference on Google.
推荐答案
与CommonsWare的答案结合在一起.这是我的解决方案:
Combined with CommonsWare's answer. Here is my solution:
我定义了一个AtomicBoolean
变量和一个函数来检查它是否正在运行测试:
I defined an AtomicBoolean
variable and a function to check whether it's running test:
private AtomicBoolean isRunningTest;
public synchronized boolean isRunningTest () {
if (null == isRunningTest) {
boolean istest;
try {
Class.forName ("myApp.package.name.test.class.name");
istest = true;
} catch (ClassNotFoundException e) {
istest = false;
}
isRunningTest = new AtomicBoolean (istest);
}
return isRunningTest.get ();
}
这避免了每次需要检查值时都进行try-catch检查,并且仅在第一次调用此函数时运行检查.
This avoids doing the try-catch check every time you need to check the value and it only runs the check the first time you call this function.
这篇关于如何检测Android应用程序是否正在使用Espresso运行UI测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!