Skip to content
This repository has been archived by the owner on Jan 10, 2024. It is now read-only.

Writing tests with Robolectric

Paulius Šukys edited this page Mar 3, 2018 · 3 revisions

Introduction

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.

Writing tests

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);

Powermock?

No. Closest approach would be:

  1. Create a shadow class
@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.

  1. Include in used shadows in test class
@Config(constants = BuildConfig.class, shadows = {MyShadowBitmap.class})
  1. Change static values in a test case.
MyShadowBitmap.SOME_STATIC_VARIABLE = "abc123";

My tests fail because of something something database cursor.. ?

Database objects cannot persist in-between tests, the database needs to be closed, else the above cryptic error shows up.

Clone this wiki locally