pivotal/robolectric — Issue #197: Using Robolectric with Junit @Parameterized
Author: pyricau
Created: 2012-02-17 10:32:15+00:00
State: open

Hi guys,

This is not really an issue, rather a kind of contribution. It's not clean enough so that I can make a fork / pull request, but it layouts the main idea, and maybe someone will be willing to do something with this.

Main idea : being able to used [Parameterized](http://junit.sourceforge.net/javadoc/org/junit/runners/Parameterized.html) tests with Robolectric.

Here are the issues :

* `Parameterized` is a custom runner, in fact it's a test Suite that generates one test runner for each set of data. Those test runners are subclasses of `BlockJUnit4ClassRunner`, and Robolectric need the runner to be an instance of `RobolectricTestRunner` in order to use its custom classloader
* `Parameterized` passes the test data through the test constructor. `Robolectric` requires an empty constructor.
* I had to do a bit of reflection to access Robolectric classloader. The method that generates the data is static and must be called from a class loaded by the Robolectric classloader.

The solution I found was to copy the `Parameterized` runner, and then hack around it to use `RobolectricTestRunner`.

Instead of passing the arguments through the constructor, you need to implement an init() method, with a matching number of arguments.

I needed to use my custom subclass of `RobolectricTestRunner`, which sets the project path, and that's mainly why I can't directly contribute this code. I don't really like the current implementation, because even if you integrate it, there will be no easy way to customize `RobolectricParameterized`.. unless you guys have some clever idea :) .

No more talking, let's dive into the code :

* a [usage example](https://github.com/excilys/androidannotations/blob/1c91e3a8e396a42733e3af49338c43ab128a28e8/AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/instancestate/SaveInstanceStateActivityParameterizedTest.java)
* the [RobolectricParameterized](https://github.com/excilys/androidannotations/blob/1c91e3a8e396a42733e3af49338c43ab128a28e8/AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/RobolectricParameterized.java) runner
* as you can see, `TestClassRunnerForParameters` is a subclass of [AndroidAnnotationsTestRunner](https://github.com/excilys/androidannotations/blob/1c91e3a8e396a42733e3af49338c43ab128a28e8/AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/AndroidAnnotationsTestRunner.java), which is in fact a simple `RobolectricTestRunner` that sets the path to a different folder.