Ilya Shinkarenko Ilya Shinkarenko -4 years ago 147
Android Question

How to determine if Android Application is started with JUnit testing instrumentation?

I need to determine in runtime from code if the application is run under TestInstrumentation.

I could initialize the test environment with some env/system variable, but Eclipse ADK launch configuration would not allow me to do that.

Default Android system properties and environment do not to have any data about it. Moreover, they are identically same, whether the application is started regularly or under test.

This one could be a solution: Is is possible to find out if an Android application runs as part of an instrumentation test but since I do not test activities, all proposed methods there won't work. The ActivityManager.isRunningInTestHarness() method uses this under the hood:

SystemProperties.getBoolean("ro.test_harness")


which always returns false in my case. (To work with the hidden android.os.SystemProperties class I use reflection).

What else can I do to try to determine from inside the application if it's under test?

Answer Source

I have found one hacky solution: out of the application one can try to load a class from the testing package. The appication classloader surprisingly can load classes by name from the testing project if it was run under test. In other case the class is not found.

private static boolean isTestMode() {
  boolean result;
  try {
    application.getClassLoader().loadClass("foo.bar.test.SomeTest");
    // alternatively (see the comment below):
    // Class.forName("foo.bar.test.SomeTest");
    result = true;
  } catch (final Exception e) {
result = false;
  }
  return result;
}

I admit this is not elegant but it works. Will be grateful for the proper solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download