2013-05-03

Continuations for Android

In simple words using "Continuations" mean you can pause the execution of code and restart at the same point later with all local variables. (You can think of it as "freezing" the stack)

While you can use threads and locks for a similar behavior but you can even persist a continuation and reload it later. While this is not something you need every day it can come handy sometimes.

While other programming languages have built in support for something like this it is not a standard feature of Java.

However there is a small and nice Apache project making this possible with Java:

http://commons.apache.org/sandbox/javaflow/

It comes with an Ant task to do byte code manipulation and a small runtime (one or two classes). Really nice!

I wondered if this could work on Android, too. (Ok - there is no reason why not but I wanted to give it a try)

YES! IT WORKS!

One thing that one should be aware of is that you really need byte code transformation done by an Ant task. While it's no problem to extend Android's ant builds we all need to run code right from Eclipse.

Fortunately there is a simple solution to this: Just create an Ant script doing whatever is needed and add a new "Builder" between "Java Builder" and "Android Package Builder". That's it!


Rethinking Android Unit Testing

After using Robolectric for a while I was looking for a different approach to do unit testing for Android.

While Robolectric met a lot of my requirements I had the need for a powerful mocking framework and decided to use PowerMock(ito). It's a really powerful framework but I wasn't able to use it together with Robolectric since both do a lot of classloader and byte code transformation magic.

So I decided to just run the test with "android.jar" from the SDK on the classpath and forget about Robolectric but instead mock the platform API calls with PowerMock(ito).

Unfortunately it turned out that this wasn't as easy as it sounds. So I decided to use Javassist to do some byte code manipulation to the android.jar before using it for unit testing. The problem with the original android.jar was that each and every method throws a "Sub"-runtime exception and PowerMock(ito) wasn't able to mock super-calls. (imagine an activity as the class-under-test which must call super.onCreate() in it's onCreate() implementation. Since it's not possible to mock the super.onCreate() you are out of luck)

This approach turned out to be the silver bullet of In-JVM Android unit testing for me.

Thanks to Javassist the transformation of the android.jar was a simple task and now I'm able to use the full potential of PowerMock(ito) to test Android code in Eclipse and during CI builds - including code coverage and all the other fancy stuff.