【问题标题】:How to detect whether android app is running UI test with Espresso如何检测 android 应用程序是否正在使用 Espresso 运行 UI 测试
【发布时间】:2015-04-17 11:48:15
【问题描述】:

我正在为 Android 编写一些 Espresso 测试。我正在运行以下问题:

为了让某个测试用例正常运行,我需要禁用应用程序中的一些功能。因此,在我的应用程序中,我需要检测我是否正在运行 Espresso 测试,以便我可以禁用它。但是,我不想使用BuildConfig.DEBUG,因为我不希望在调试版本中禁用这些功能。另外,我想避免创建新的 buildConfig 以避免创建太多的构建变体(我们已经定义了很多风格)。

我正在寻找一种方法来定义 buildConfigField 以进行测试,但我在 Google 上找不到任何参考。

【问题讨论】:

  • 一个 hacky 解决方案是 Class.forName() 以查看您的测试代码是否在 VM 中:wtanaka.com/node/8041
  • 这个问题你解决了吗?
  • 是的。我要发布我的解决方案

标签: android android-espresso ui-testing


【解决方案1】:

结合 CommonsWare 的评论。这是我的解决方案:

我定义了一个AtomicBoolean 变量和一个函数来检查它是否正在运行测试:

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 检查,并且仅在您第一次调用此函数时运行检查。

【讨论】:

  • 只使用布尔(不是布尔)对象而不是 AtomicBoolean 类怎么样?
  • AtomicBoolean 的这种使用不是线程保存。您需要使用单个最终 AtomicBoolean 的设置器,而不是检查 null 并创建一个新的。目前,这与使用普通的boolean 一样保存。
  • 但是如果方法是同步的,那么一个 volatile 布尔值(用于可见性的 volatile 值)应该就足够了,而且完全是线程安全的,对吧?
【解决方案2】:

结合 Commonsware 注释 + Comtaler 的解决方案,这是一种使用 Espresso 框架为任何测试类执行此操作的方法。

private static AtomicBoolean isRunningTest;

public static synchronized boolean isRunningTest () {
    if (null == isRunningTest) {
        boolean istest;

        try {
            Class.forName ("android.support.test.espresso.Espresso");
            istest = true;
        } catch (ClassNotFoundException e) {
            istest = false;
        }

        isRunningTest = new AtomicBoolean (istest);
    }

    return isRunningTest.get();
}

【讨论】:

  • 还有一点,迁移到androidX后应该是->Class.forName("androidx.test.espresso.Espresso")
【解决方案3】:

BuildConfig 类中的标志怎么样?

android {
    defaultConfig {
        // No automatic import :(
        buildConfigField "java.util.concurrent.atomic.AtomicBoolean", "IS_TESTING", "new java.util.concurrent.atomic.AtomicBoolean(false)"
    }
}

在你的测试类中添加这个。

static {
    BuildConfig.IS_TESTING.set(true);
}

【讨论】:

  • 这帮助我避免为测试时需要不同的一行编写大量代码
【解决方案4】:

基于上面的答案,以下 Kotlin 代码是等效的:

val isRunningTest : Boolean by lazy {
    try {
        Class.forName("android.support.test.espresso.Espresso")
        true
    } catch (e: ClassNotFoundException) {
        false
    }
}

然后您可以检查该属性的值:

if (isRunningTest) {
  // Espresso only code
}

【讨论】:

  • androidx.test.espresso.Espresso 用于喷气机
【解决方案5】:

我不喜欢使用在 android 上运行缓慢的反射。我们大多数人都为依赖注入设置了 dagger2。我为测试设置了一个测试组件。以下是获取应用模式(测试或正常)的简要方法:

创建一个枚举:

public enum ApplicationMode {
    NORMAL,TESTING;
}

和一个普通的 AppModule:

@Module
public class AppModule {

    @Provides
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.NORMAL;
    }
}

创建一个像我一样的测试运行器:

public class PomeloTestRunner extends AndroidJUnitRunner {

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return super.newApplication(cl, MyTestApplication.class.getName(), context);
    }
}

不要忘记像这样在 gradle 中声明它:

defaultConfig {
testInstrumentationRunner "com.mobile.pomelo.base.PomeloTestRunner"
}

现在创建一个 AppModule 的子类,其重写方法看起来与此完全一样,并且不要将其标记为类定义上方的模块:

public class TestAppModule extends AppModule{

    public TestAppModule(Application application) {
        super(application);
    }

    @Override
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.TESTING; //notice we are testing here
    }
}

现在在您在自定义测试运行器中声明的 MyTestApplication 类中声明了以下内容:

public class PomeloTestApplication extends PomeloApplication {

    @Singleton
    @Component(modules = {AppModule.class})
    public interface TestAppComponent extends AppComponent {
        }

    @Override
    protected AppComponent initDagger(Application application) {
        return DaggerPomeloTestApplication_TestAppComponent.builder()
                .appModule(new TestAppModule(application)) //notice we pass in our Test appModule here that we subclassed which has a ApplicationMode set to testing
                .build();
    }
}

现在要使用它,只需将其注入生产代码中,如下所示:

@Inject
    ApplicationMode appMode;

因此,当您运行 espresso 测试时,它将测试枚举,但在生产代码中,它将是普通枚举。

ps 不是必需的,但如果您需要查看我的生产匕首如何构建图形并在应用程序子类中声明:

 protected AppComponent initDagger(Application application) {
        return DaggerAppComponent.builder()
                .appModule(new AppModule(application))
                .build();
    }

【讨论】:

    【解决方案6】:

    如果您将 JitPack 与 kotlin 一起使用。您需要更改 Espresso 的 包装名称。

    val isRunningTest : Boolean by lazy {
        try {
            Class.forName("androidx.test.espresso.Espresso")
            true
        } catch (e: ClassNotFoundException) {
            false
        }
    }
    

    检查

    if (isRunningTest) {
      // Espresso only code
    }
    

    【讨论】:

    • 格式化:选择代码并点击编辑器中的{}图标
    【解决方案7】:

    我将创建两个如下所示的文件

    src/main/.../Injection.java

    src/androidTest/.../Injection.java

    在 Injection.java 中我将使用不同的实现,或者只是一个静态变量 int。

    由于 androidTest 是源集,而不是构建类型的一部分,我认为你想做的事情很难。

    【讨论】:

    • 我怀疑在测试这两个文件是否放入同一个包时会导致构建错误...
    【解决方案8】:

    您可以为此使用 SharedPreferences。

    设置调试模式:

    boolean isDebug = true;
    
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("DEBUG_MODE", isDebug);
    editor.commit();
    

    检查是否调试模式:

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    boolean isDebug = sharedPref.getBoolean("DEBUG_MODE", false);
    
    if(isDebug){
        //Activate debug features
    }else{
        //Disable debug features
    }
    

    【讨论】:

    • 不回答问题。
    【解决方案9】:

    这是一种为 react-native Android 应用调整公认解决方案的方法。

    // MainActivity.java
    
    // ...
    
      @Override
      protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
    
          // ...
    
          @Override
          protected Bundle getLaunchOptions() {
            Bundle initialProperties = new Bundle();
            boolean testingInProgress;
    
            try {
              Class.forName ("androidx.test.espresso.Espresso");
              testingInProgress = true;
            } catch (ClassNotFoundException e) {
              testingInProgress = false;
            }
    
            initialProperties.putBoolean("testingInProgress", testingInProgress);
    
            return initialProperties;
          }
        };
      }
    }
    

    然后,您将能够访问 testingInProgress 作为最顶层组件(通常是 App.js)的道具。从那里您可以使用componentDidMount 或等效的方法来访问它并将其放入您的 Redux 商店(或您正在使用的任何东西),以便您的应用程序的其余部分可以访问它。

    我们使用它来触发我们应用中的一些逻辑,以帮助我们使用 fastlane 截屏。

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2015-11-26
      • 2019-11-22
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多