Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether android app is running UI test with Espresso

I am writing some Espresso tests for Android. I am running in the the following problem:

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).

I was looking for a way to define buildConfigField for test but I couldn't find any reference on Google.

like image 856
Comtaler Avatar asked Feb 16 '15 21:02

Comtaler


People also ask

Where are Android UI tests?

To run instrumented UI tests using Android Studio, you implement your test code in a separate Android test folder - src/androidTest/java . The Android Plug-in for Gradle builds a test app based on your test code, then loads the test app on the same device as the target app.

How do I test my UI app?

Checklist for Testing Mobile App UITest overall color scheme and theme of the app on the device. Check the style and color of icons. Test the look and feel of the web content across a variety of devices and network conditions.

What is Espresso UI Test?

Espresso is an open source android user interface (UI) testing framework developed by Google. The term Espresso is of Italian origin, meaning Coffee. Espresso is a simple, efficient and flexible testing framework.


1 Answers

Combined with CommonsWare's comment. Here is my solution:

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 (); } 

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.

like image 72
Comtaler Avatar answered Sep 22 '22 19:09

Comtaler