Detect Espresso UI Test in Android App: How-To
In this article
You can detect whether your Android app is running under an Espresso UI test by checking for Espresso-specific system properties, inspecting the classpath for Espresso classes, or using a simple flag set by a custom test runner. The most reliable method is to check System.getProperty("espresso.test") or look for the presence of androidx.test.espresso classes at runtime. This lets you conditionally disable animations, skip analytics, or adjust logging without affecting production builds.
What You'll Need
- Android Studio with your app project open (Kotlin or Java).
- Espresso dependencies already added to your
androidTestconfiguration (e.g.,androidx.test.espresso:espresso-core). - A basic understanding of Gradle build variants and instrumentation tests.
Step-by-Step
- Check for the Espresso system property. Espresso sets the system property
espresso.testtotruewhen it initializes. In your app code, callSystem.getProperty("espresso.test")and compare it to"true". This property is only present during Espresso test runs, so it is a lightweight check that does not require importing test libraries into your production code. - Verify the property is set. If you are unsure, add a temporary log statement in your test setup (e.g., in a
@Beforemethod) to printSystem.getProperty("espresso.test"). Run a single Espresso test and confirm the output istrue. If it isnull, your Espresso version may not set this property by default; proceed to the next step. - Use a custom test runner flag (fallback). If the property is not set, create a custom
AndroidJUnitRunnersubclass in yourandroidTestsource set. OverrideonCreateand callSystem.setProperty("espresso.test", "true")beforesuper.onCreate. Then configure yourtestInstrumentationRunnerinbuild.gradleto use this custom runner. This guarantees the flag is present for all Espresso tests. - Check for Espresso classes on the classpath. As an alternative, attempt to load a known Espresso class using reflection:
Class.forName("androidx.test.espresso.Espresso"). If it succeeds, Espresso is on the classpath. Wrap this in a try-catch forClassNotFoundException. This method works even if the system property is missing, but it may also return true if Espresso is present as a compile-time dependency in a non-test build (rare). - Encapsulate the check in a utility class. Create a small helper (e.g.,
TestDetector) with a static boolean methodisRunningEspressoTest()that combines the property check and the classpath check. Call this method from your app code where you need to alter behavior. Keep the helper in your main source set so it is accessible from both production and test code. - Use the flag to adjust app behavior. For example, disable animations by setting
Settings.Global.ANIMATOR_DURATION_SCALEto0(requiresWRITE_SECURE_SETTINGSpermission, typically granted via ADB in test environments) or skip network calls. Always guard these changes with the detector so production users are unaffected. - Test the detection logic. Write a simple Espresso test that asserts your
isRunningEspressoTest()returnstrue. Also run a manual build (non-test) and verify it returnsfalse. This confirms the detection works as intended.
Common Mistakes
- Relying solely on
BuildConfig.DEBUG. Debug builds are not always test builds; Espresso can run on release variants too. Use the Espresso-specific checks instead. - Importing test libraries into production code. Avoid direct references to Espresso classes in your main source set; use reflection or system properties to keep production APKs clean.
- Forgetting to set the custom runner in Gradle. If you create a custom runner but do not update
testInstrumentationRunner, the flag will never be set. - Assuming the property is always set. Older Espresso versions or certain configurations may not set
espresso.test. Always have a fallback. - Checking for Espresso in the wrong process. Instrumentation tests run in the app's process, but some background services may run in separate processes where the property is not visible. Keep checks in the main process.
Tips
- Use a single utility method to centralize detection logic; this makes it easy to update if Espresso changes its behavior.
- Combine multiple signals (property, classpath, custom flag) for robustness, but avoid over-engineering—start with the property check.
- Document the detection in your code so future developers understand why it exists.
- Consider using Gradle build types or flavors to inject a boolean resource instead of runtime checks, if you control the test build configuration.
- When disabling animations for tests, remember to re-enable them after the test run if you are using a shared device or emulator.
Troubleshooting
- The property is null during tests. Ensure you are using a recent Espresso version. If not, implement the custom runner flag as described in Step 3.
- Class.forName throws an exception. Espresso may not be on the classpath if you are running a different test framework. Verify your
androidTestdependencies include Espresso. - Detection works in one test but not another. Check if the test runs in a separate process or uses a different runner. Standardize on one runner across all tests.
- App behaves differently in production. Double-check that your detection method does not have false positives. Log the detection result in both test and production builds to compare.
- Custom runner not applied. Confirm the
testInstrumentationRunnerline in yourbuild.gradlepoints to your custom runner class, and that the class is in theandroidTestsource set.
Frequently Asked Questions
Can I detect Espresso without modifying production code?
Yes, by using a custom test runner that sets a system property, you can keep production code free of test-specific imports. The production code only reads the property.
Does Espresso always set the espresso.test property?
Not guaranteed across all versions. It is set by default in many recent versions, but always have a fallback like a custom runner flag.
Will this work with Robolectric tests?
No, Robolectric runs on the JVM and does not use Espresso's instrumentation. Use a different detection method for Robolectric, such as checking for the Robolectric test runner.
Is checking for Espresso classes reliable?
It can produce false positives if Espresso is included as a compile-time dependency in a non-test build. Use it as a secondary check, not the primary one.
Can I use this to disable animations automatically?
You can, but disabling animations via Settings.Global requires the WRITE_SECURE_SETTINGS permission, which is not granted to normal apps. In test environments, you can grant it via ADB. Alternatively, use Espresso's built-in idling resources instead of disabling animations.
What if my app uses multiple processes?
The system property is set per-process. If your app has multiple processes, you may need to set the property in each process or use a shared flag (e.g., a file or shared preference) set by the test runner.