Thursday, November 22, 2012

How to fire event from AUT to other app using robotium / instrumentation

IMPORTANT: Code will work only on rooted device or emulator.

Many times we are required to test an andorid app which talks to any other app like (messaging, web browser etc.) As robotium or android intrumention does not allow us to access other apps from within test code we end up testing that feature manually which is a big obstacle in automating AUT.

While trying to automate one of the android app which uses messaging, email and other features of device, we also got stuck with this problem. We googled a lot and thankfully we found some solution to our problem which we think of worth sharing with all.

First approach:
The first and simplest approach is using adb shell command to perform required operation on device/emulator. Here is the sample command where running adb command to come back from third party app.
                   Runtime.getRuntime().exec("adb shell input keyevent 4");

Here 4 is the keycode for Back key.
This approach is very useful when you have only apk file and you are not able to modify manifest file of AUT.

Second approach:
Second approach is using INJECT_EVENTS permission in the manifest file of AUT. But problem with this approach is you need to put your AUT in sys app folder of emulator/device and for which you need system certificate. If you do not have system certificate then you need to root your device or run this test on emulator. Steps are mentioned below:
  1.  Add INJECT_EVENTS permission tag in the manifest file of AUT.
  2.  Build AUT with android debug certificate and get apk file. 
  3.  Download RootExplorer.apk or similar app from internet and install it on desired emulator/device. 
  4.  Copy apk file of AUT to the emulator/device (DO NOT install yet), preferrably on sdcard. e.g. adb push AUT.apk /sdcard/ 
  5. Open RootExplorer and go to /sdcard and copy apk file of AUT. 
  6. Make sure current mode is R/W. To switch to R/W mode there is a button provided at the top left corner on RootExplorer screen.  
  7. Navigate to /system/apps folder and paste apk file of AUT. 
  8. Install AUT by tapping on it 
  9. Now from your code you can fire any event when AUT interacts with other external activity e.g. If AUT has a button and clicking on it launches web browser then to navigate back from web browser to AUT you can use 
                 Instrumentation inst = getInstrumentation();
                 inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); 

 This approach gives us more flexibility and control over other app and is very useful if we have code of AUT.