Many aspects of Robolectric can be configured at runtime by subclassing RobolectricTestRunner to create a custom test runner.
By default, Robolectric will look for your AndroidManifest.xml file in the current working directory, and will look for your resource files in the "res" directory in the same place.
You can override these defaults in your custom test runner by specifying alternate values in the super constructor call:
public class CustomTestRunner extends RobolectricTestRunner {
public CustomTestRunner(Class testClass) throws InitializationError {
// defaults to "AndroidManifest.xml", "res" in the current directory
super(testClass, new File("../other/project-root"));
}
}
By default, Robolectric will create a new instance of the application class specified in AndroidManifest.xml for each test.
You may override this behavior in your custom test runner by overriding the createApplication method:
public class CustomTestRunner extends RobolectricTestRunner {
public CustomTestRunner(Class testClass) throws InitializationError {
super(testClass);
}
@Override protected Application createApplication() {
return new CustomApplication();
}
}
Robolectric resets some internal state automatically before every test, including:
Robolectric provides hooks for specifying your own code to run before and after every test in every test class that uses your test runner. This can be especially useful for resetting state between tests, or triggering dependency injection (e.g. with RoboGuice).
public class CustomTestRunner extends RobolectricTestRunner {
public CustomTestRunner(Class testClass) throws InitializationError {
super(testClass);
}
@Override public void prepareTest(Object test) {
}
@Override public void beforeTest(Method method) {
}
@Override public void afterTest(Method method) {
}
}
Robolectric provides shadow implementations of many Android classes, but you may find that you want to add your own, or change the way a shadow works. You can do this by registering your shadow classes in the beforeTest(Method method) method.
public class CustomTestRunner extends RobolectricTestRunner {
public CustomTestRunner(Class testClass) throws InitializationError {
super(testClass);
}
@Override public void beforeTest(Method method) {
Robolectric.bindShadowClass(ShadowBitmapFactory.class);
Robolectric.bindShadowClass(ShadowDrawable.class);
Robolectric.bindShadowClass(ShadowGeocoder.class);
}
}