Introduction

I probably don’t need to tell why testing application is important. Unit testing is good for preventing regression, avoiding null pointers and by using TDD - code which is created is minimal and usually has good API. For more testing related topics I recommend reading Uncle Bob’s blog.

Google is pushing Gradle as standard build system for Android - which is, in my opinion, really good - but what if we’re using old build system? I didn’t find many posts about setting up Intellij with Robolectic so decided to write this post.

I won’t explain what Robolectric is, since if you’re here, you probably know about it.

I will explain how to setup it with appcompat support library, because when I was using it I encountered problem so we will kill two birds with one stone.

Let’s say we have our project setup with appcompat like in image below:

Project setup

Robolectric project

As far as we all know, we cannot use normal junit because of famous stub exception:

Caused by: java.lang.RuntimeException: Stub!

Google has made instrument testing (Android Unit Testing) but it has one disadvantage - you need to have emulator turned on. It takes some time so to avoid it, let’s setup robolectric.

In Intellij open project settings and add new Android Test Module:

Robolectic Test Module

Now we need to add dependencies. Since we don’t use any dependency management build system, dependencies might become troublesome. But fortunately there’s robolectric build with dependencies - robolectric-jar-with-dependencies. You can download this file from here: Sonatype Repository.

Note: Robolectic doesn’t support appcompat until version 2.3 so be sure to get at least 2.3!

We will also need junit and hamcrest-core lastest versions are fine.

Finally we need to add dependency to our main project. In the end it should look like on this:

Final project setup

Please look at the scope of dependencies marked with red circle - you need to set them as test.

Note: take a look at the order of dependecies - it’s the best to set Robolectric first in classpath (it must be before android and project dependency)

Finally let’s create our test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.example.myapp;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;

import static org.junit.Assert.assertNotNull;


@RunWith(RobolectricTestRunner.class)
public class MyActivityTest {

  @Test
  public void shouldNotBeNull() {

  	MyActivity myActivity = Robolectric
            .buildActivity(MyActivity.class).create()
            .start()
            .resume()
            .visible()
            .get();

  	assertNotNull(myActivity);

  }

}

Run it as Junit Test and you should get a green bar!