Add Robolectric to AndroidKickstartR Generated Project

Here is quick HOWTO and up to date alternative to Robolectric’s maven quick start guide.

TLDR: Look at this gist.

Project Creation

First of all make sure you’ve a maven 3 version installed on your system.

mvn3 -v
Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)

AndroidKickstartR

Follow instructions on AndroidKickstartR, make sure ‘Android-Maven-Plugin’ is checked, since that’s is only what we focused on here.

Make sure the project is working with mvn clean install, see maven related documentation on AndroidKickstartR.

Robolectric

Add dependencies

Update your project pom.xml file:

  1. Add the following lines right after <modelVersion>4.0.0</modelVersion>

     <parent>
         <groupId>org.sonatype.oss</groupId>
         <artifactId>oss-parent</artifactId>
         <version>5</version>
     </parent>
    
  2. Add Robolectric dependencies right before </dependencies>:

     <dependency>
         <groupId>org.robolectric</groupId>
         <artifactId>robolectric</artifactId>
         <version>2.0-alpha-3-SNAPSHOT</version>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.8.2</version>
         <scope>test</scope>
     </dependency>
    

Look at this gist for example.

And finally type: mvn clean install

Verify your setup

Our first test, add the following file into the src/test/java directory:

MainActivityTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import me.yevgenko.kickfoobar.MainActivity; // fix package prefix
import me.yevgenko.kickfoobar.R; // fix package prefix
import org.robolectric.RobolectricTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(RobolectricTestRunner.class)
public class MainActivityTest {

    @Test
    public void shouldHaveHappySmiles() throws Exception {
        String appName = new MainActivity().getResources().getString(R.string.app_name);
        assertThat(appName, equalTo("Your App Name Here"));
    }
}

Typing: mvn clean test will run the tests.

When running tests from within IntelliJ or Eclipse, be sure to run tests using the JUnit runner, not the Android Test runner.

Happy Testing! :)

Comments