Saturday, April 27, 2013

Parametrized unit test for JUnit and Android (DataSet)

Developing for Android I found testing difficult. Especially when it comes to Unit Testing. Lets be honest Android doesn't provide options to do proper unit test (no, if it begins with "create an instrumentation test", it is not unit test). Third party frameworks (eg. Robolectric) can be used to mock Android classes. They require you to use their test runner, or extend that. This can't be combined with the Parametrized runner of JUnit (which could be used to run a bunch of input parameters against the same test method). Thankfully JUnit has an other powerful extension, called Rules. I've created a package to provide a Parametrized (or DataSet) like annotation.

DataSet package

  • can be used with any TestRunner (eg. with Robolectric Runner)
  • can have multiple datasets in the same test class (and different test methods can use either of them)
  • can set expected exceptions (and they can be different for each testVector)
  • can have run time generated dataset
Note: at least JUnit 4 is needed to use this, since Rules were introduced in that.

If you use it, I would be delighted, if you could let me know. It is always good feeling when someone else finds my work useful :-).


Anonymous said...


I was interested in your DataSet package as it should solve a similar problem of mine. I am using robotium and an extended testrunner to export robotium results as xml therefore I could not use Junit parametrized tests.

However, I am struggling with your package. I added the 1.1 version of your package into my lib folder, included the library in the project, and did something very similar to your example 1. However, rule.getXXXX is throwing a NullPointerException even when the index is set to 0 with a properly created DataSet class.

Any idea of what could be wrong ?

Anyway, thanks for the package

Al_th said...

Figured out what was the problem.

Unfortunately, parametrized runner is part of JUnit 4 framework. As of today, ""Note that the Android testing API supports JUnit 3 code style, but not JUnit 4".

Therefore, it is not possible to use your DataSet package with Robotium.

As unfortunate as this is, thank you for your package, I keep it up one's sleeve (Hope this is the good english expression :p)


MikiNW said...

Yes, sorry, I didn't mention that in the description. Thank you for driving my attention. I will modify the description.

Anonymous said...

Thanks for this, looks amazing