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

Building on the answers above the following Kotlin code is equivalent:

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

You can then check the value of the property:

if (isRunningTest) {
  // Espresso only code
}

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.


Combining Commonsware comment + Comtaler's solution here's a way to do it for any test class using the Espresso framework.

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