Thursday, September 08, 2011

Android Testing: Running tests from code


I was answering some questions at StackOverflow today and one caught my attention. It was asking, well, not directly but I understood this was the intention, how to run the tests not from another computer using adb or Eclipse but from an android application itself. Then, here we are presenting a solution to run instrumentation from code.



private void runTests() {
   final String packageName = getPackageName();
   final List<InstrumentationInfo> list = 
         getPackageManager().queryInstrumentation(packageName, 0);
   if ( list.isEmpty() ) {
      Toast.makeText(this, "Cannot find instrumentation for " + packageName,
         Toast.LENGTH_SHORT).show();
      return;
   }
   final InstrumentationInfo instrumentationInfo = list.get(0);
   final ComponentName componentName = 
         new ComponentName(instrumentationInfo.packageName,
         instrumentationInfo.name);
   if ( !startInstrumentation(componentName, null, null) ) {
      Toast.makeText(this, "Cannot run instrumentation for " + packageName,
         Toast.LENGTH_SHORT).show();
   }
}


You need a valid context to call startInstrumentation() so this is probably added to an Activity.

I can imagine only a valid use case for this, which is running the tests when you don't have the device connected to a computer.
Do you have another use case ?
Speak out.

Hope this helps.