Search code examples
androidandroid-gradle-pluginandroid-espressobuildconfig

Is there a way to set a build config field for Espresso tests (or something similar)?


I'm working on automated testing in Android, and I'm trying to figure out a way to determine - in code - if it's being executed via Espresso or not. I've come across the following:

ActivityManager.isRunningInTestHarness()

but that doesn't work. Is there something similar I can do? Is there a way to add a buildConfigField for an Espresso test in build.gradle?


Solution

  • One way to reliably find out whether your app is running instrumented by your test suite is to try to load a test suite class:

    private boolean isInstrumentedRun() {
        boolean result;
        try {
            getApplication().getClassLoader().loadClass(
                    "my.fully.qualified.TestProjectClass");
            result = true;
        } catch (final Exception e) {
            result = false;
        }
        return result;
    }