Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 it 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?

like image 370
Ilya Shinkarenko Avatar asked Jan 26 '14 18:01

Ilya Shinkarenko


People also ask

What is Android instrumentation testing?

Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.

What is instrumentation in mobile testing?

Instrumentation is a process to prepare the application for testing or automation. Part of the instrumentation process may add "instruments" that allow the testing framework to gain access to parts of the application. Perfecto provides tools for instrumenting mobile applications for different purposes.

Which Java framework is used to write unit tests in Android?

Mockito. Mockito is an open-source and one of the preferred Java unit testing frameworks. This well-known Java-based mocking framework is primarily used for Java app unit testing.


1 Answers

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.

like image 81
Ilya Shinkarenko Avatar answered Oct 18 '22 10:10

Ilya Shinkarenko