如何使用 Espresso 检测 android 应用程序是否正在运行 UI 测试 [英] How to detect whether android app is running UI test with Espresso

查看:37
本文介绍了如何使用 Espresso 检测 android 应用程序是否正在运行 UI 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 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 comment. 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.

这篇关于如何使用 Espresso 检测 android 应用程序是否正在运行 UI 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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