Monday, March 12, 2012

monkeyrunner: running unit tests

First of all, I hope you like the new look of the blog. Personally I think the darker background turns the posts more relevant and less distracting.

Let me know what you think.

Now, to the point. We have presented an analyzed here many monkeyrunner scripts and techniques but we haven't explicitly created some unit tests, and this is precisely what we are going to do.

As our Application Under Test (AUT) we are using the well-known Temperature Converter, which was used many times to demonstrate other concepts as well.
The source code is as usual available through github.

Additionally, we are also using the help of AndroidViewClient which is available at github too and was introduced in monkeyrunner: interacting with the Views. The central idea is to use AndroidViewClient facilities to create a unit test. Let's name this script

#! /usr/bin/env monkeyrunner

Created on 2012-03-08

@author: diego

import sys
import unittest
import subprocess
import socket
import re
from import MonkeyRunner, MonkeyDevice
import viewclient

class TemperatureConverterActivityTests(unittest.TestCase):

   def setUp(self):
      # connect to the device
      self.device = MonkeyRunner.waitForConnection(60)
      self.assertNotEqual(None, self.device)

      # start TemperatureConverter

      # clear the field
      for n in range(10):'DEL', MonkeyDevice.DOWN_AND_UP)

      # create the client
      self.viewclient = viewclient.ViewClient(self.device)

   def tearDown(self):

   def testConversion(self):
      C = '123'
      F = '253.4'



      celsius = self.viewclient.findViewById('id/celsius')['mText']
      fahrenheit = self.viewclient.findViewById('id/fahrenheit')['mText']

      self.assertEqual(celsius, C)
      self.assertEqual(fahrenheit, F)

if __name__ == '__main__':

It is noticeable how the use of AndroidViewClient simplifies this test.

So if everything goes well, providing that your emulator or device is running and reachable, you will receive this output for the test run:

$ ./ 
Ran 1 test in 8.801s


Hope this helps.
Post a Comment