-
-
Notifications
You must be signed in to change notification settings - Fork 86
Writing tests with Robolectric
Robolectric framework replaces Android SDK so that tests that use Android internals can run on JVM. This allows to run tests quickly and without exhausting lots of resources (Friendlier for Continuous Integration server).
In essence Android internals are replaced by Robolectric shadows which are the core of the framework.
Robolectric documentation itself is quite short but sufficient for initial view.
Each Robolectric class starts with runner annotation:
@RunWith(RobolectricTestRunner.class)
Robolectric wraps up activities in its lifecycle so that they can be test.
MyActivity activity = Robolectric.setupActivity(MyActivity.class);
No. Closest approach would be:
@Implements(Bitmap.class)
public class MyShadowBitmap {
public static String SOME_STATIC_VARIABLE = "default value";
...
public void someMethod(...) {
return SOME_STATIC_VARIABLE;
}
}
For Android classes, please view related Shadow class that needs to be extended.
- Include in used shadows in test class
@Config(constants = BuildConfig.class, shadows = {MyShadowBitmap.class})
- Change static values in a test case.
MyShadowBitmap.SOME_STATIC_VARIABLE = "abc123";
Database objects cannot persist in-between tests, the database needs to be closed, else the above cryptic error shows up.