Finding Your Application
By default, Robolectric first looks in your AndroidManifest.xml for the class to load as your application:<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp">
<application android:name=".Application"/>
</manifest>
That will cause a class called com.myapp.Application to be loaded. However, if you create a class with the same name and package, but with "Test" prepended to the class name, Robolectric will load that instead.
package com.myapp;
class TestApplication extends Application {
}
The Application Lifecycle
Robolectric now automatically calls an application's onCreate() method before the test runs, and onTerminate() after the test runs. Note that this a change from earlier versions. If you want to prevent your application's onCreate() method from being called, you can override it in a test class and have it do nothing.
If your test application implements the TestLifecycleApplication interface, it will get called with a few more useful events:
class TestApplication extends Application
implements TestLifecycleApplication {
@Override public void beforeTest(Method method) {
}
@Override public void prepareTest(Object test) {
}
@Override public void afterTest(Method method) {
}
}
implements TestLifecycleApplication {
@Override public void beforeTest(Method method) {
}
@Override public void prepareTest(Object test) {
}
@Override public void afterTest(Method method) {
}
}
The overall steps taken when running each test, then, are:
- Create your application.
- Call application.onCreate().
- Call application.beforeTest().
- Call application.prepareTest().
- Run the test.
- Call application.onTerminate().
- Call application.afterTest().
These changes should make it possible for many people to avoid overriding RobolectricTestRunner altogether. Note that you can still change this by using your own subclass of RobolectricTestRunner, which provides a different TestLifecycle class.