How to write Android unit tests using Robolectric

Erika Tan
AndroidPub
Published in
4 min readFeb 6, 2018

We can all relate to how annoying it might be to hit the “run” button in Android Studio, only to find yourself having to wait for a while for the emulator to generate, load, and build your project. Thankfully, testing libraries and frameworks have been created to prevent us from doing this all the time. Continuing from my previous guide where we looked at the basics of Android testing, we’ll now be looking at how to set up Robolectric in your project and use it to write unit tests!

Setting it up

The very first thing you’ll need to do, as with all other frameworks, is add Robolectric using Gradle or Maven. If you’re using Maven, just add this dependency to your pom.xml:

<dependency>
<groupId>org.robolectric</groupId>
<artifactId>robolectric</artifactId>
<version>3.6.1</version>
<scope>test</scope>
</dependency>

If you’re using Gradle, follow these steps:

  • Go to your build.gradle file and and add testImplementation "org.robolectric:robolectric:3.6.1" to your dependencies.
  • While you’re still in build.gradle, add unitTests.includeAndroidResources like so:
android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
  • If you’re using Mac or Linux, you should also configure the default JUnit test runner to address one of the bugs that appear in Android Studio. At the top menu, select Run, then click on Edit Configurations. After that, open the Defaults menu and select Android JUnit. Change the working directory to $MODULE_DIR$ .

Now you’re ready to write your first unit test!

Writing the test

When you create a unit test, it should be located at module-name/src/test/java/. This is what it looks like for this app called PowerUp (an educational mobile game for preadolescent girls created by the Systers Community):

The unit tests will be in the folder which has “(test)” next to it. Now all you need to do is add a new Java Class to that folder, and add a couple of annotations (RunWith and Config) at the top.

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class ExampleTest {
// test code goes here
}

Now, this part is optional, but you can also create a setup stub that builds the activity you’re testing before you do any of the actual testing. It looks like this:

@Before
public void setUp() throws Exception {
activity = Robolectric.buildActivity(ProsAndConsActivity.class)
.create()
.resume()
.get();
}

Here, we’re building the ProsAndConsActivity first so that we can perform tests on it later. The alternative to this would be to include ProsAndConsActivity activity = Robolectric.setupActivity(ProsAndConsActivity.class); as the first line of the test stub. The following stubs will then do the actual testing. First ,we should make sure that the activity isn’t null when we build it. We can do this with a short and sweet line of code:

@Test
public void shouldNotBeNull() throws Exception {
assertNotNull(activity);
}

Congrats, you just wrote your first test stub! ^_^

But of course we won’t stop there. Let’s make things a little harder by writing a test to check that the right activity is launched after pressing a button. We can do this using Shadow Applications. Simply import org.robolectric.Shadows and org.robolectric.ShadowActivity , and you’re halfway there!

Alright, so now that we’ve got it set up, let’s actually write the test. As an example, in PowerUp’s ProsAndConsActivity there’s a continue button that’s on the screen. When the user clicks the continue button, the MinesweeperGameActivity is supposed to be launched next. The following lines of code will test if this actually happens or not.

@Test
public void continueShouldLaunchMineActivity() {
// define the expected results
Intent expectedIntent = new Intent(activity, MinesweeperGameActivity.class);
// click the continue button
activity.findViewById(R.id.continue_button).callOnClick();
// get the actual results
ShadowActivity shadowActivity = Shadows.shadowOf(activity);
Intent actualIntent = shadowActivity.getNextStartedActivity();
// check if the expected results match the actual results
assertTrue(expectedIntent.filterEquals(actualIntent));
}

Congrats, now you can really feel good about yourself! :)

If you’ve followed along up until this point with your own app, your test class should look similar to this.

To run your test, simply right-click your test class in the navigation bar on the left and press Run.

All tests passed :)

In a nutshell

  • First, add Robolectric using Gradle or Maven.
  • To write a test, create a Java Class in your project test folder. Add RunWith and Config annotations.
  • Use a Before annotation for setting up your activity, and use Test annotations for each test stub.
  • Now that you know how to write your own tests using Robolectric, I encourage you to see what else you can test within your own app. If you want to know more about testing, check out my other article about Android testing basics. Happy Coding!

--

--