Monday, December 07, 2009

Android Testing: External libraries

We are now applying all the techniques discussed in previous posts to test our android projects.

However, all the projects reviewed were so simple that no one used external libraries so we never faced the problem of using them from our tests.

In this example we are using a dummy external library we have called libdummy-0.0.1-SANPSHOT.jar. In our Activity we are creating an object from one of the library's classes.

When we write the tests and we need to resolve the references to that objects we may feel tempted to include libdummy in test project's external jars, but doing so

[2009-12-07 16:01:14 - TCTDD11Test]Launching instrumentation android.test.InstrumentationTestRunner on device emulator-5554
[2009-12-07 16:01:25 - TCTDD11Test]Test run failed: Class ref in pre-verified class resolved to unexpected implementation
[2009-12-07 16:01:25 - TCTDD11Test]Test run complete

we receive the previous error.

The solution is to export the external jar from the main project. Open project Properties and edit Java Build Path to include the external library

and export it to be contributed to dependent test project

and this will cause no problems running the tests.

Update: Android Compatibility library: Testing Fragments
The aforementioned solution can also be applied to the android-support.jar, the library needed to support Fragments in pre-Honeycomb versions. As before, this should be exported in the main project and used in tests.

Hope this helps.

Update: Using ant
Sometimes you may want to use ant to build your projects, for example when you are building using a Continuous Integration server like Hudson, Jenkins, Bamboo, CruiseControl or similar.
To achieve this goal the easiest way is to update the main and test projects using the android update project and android update test-project commands.
The missing step using this approach is the inclusion of the external libraries we used in our previous examples. In the libs directory of the main project include the used libraries. It's preferable to create symbolic links so they are automatically updated if you update the libraries by any mean.
This is how the libs directory will look like:

$ ls -l libs
total 16
lrwxr-xr-x 1 diego staff 82 1 Aug 18:13 android-support-v4.jar -> ../../../../opt/android-sdk/extras/android/compatibility/v4/android-support-v4.jar
lrwxr-xr-x 1 diego staff 46 1 Aug 18:29 libdummy-0.0.1-SNAPSHOT.jar -> ../../libdummy/lib/libdummy-0.0.1-SNAPSHOT.jar

Having done so, you will be able to create you application using ant debug and run the tests by ant run-tests and the libraries will be automatically included in the test project.
Post a Comment