Wednesday, October 9, 2013

How to add unit tests to Android Studio project

Modify the build.gradle file

First of all remeber to modify the module's build.gradle file and not the one in the project.
In the android, defaultConfig section add this

testPackage "<package>.test"
testInstrumentationRunner "android.test.InstrumentationTestRunner"

In the dependencies section add this

instrumentTestCompile 'junit:junit:3.8'

Save the file and click the Sync Project with Gradle Files button.

Add unit tests

Under <Project>, <Module>, src add a folder named instrumentTest. Under this create a folder named java and here create a new package named <package>.test.

Now create a class named <ClassName>Test that inherits from android.test.InstrumentationTestCase. In this class individual tests of the class <ClassName> can be written, e.g.

public void testSomeMethodInClass() throws Exception {
    final int expected = 1;
    final int actual = Class.Method();
    assertEquals(expected, actual);
}

Execute test

Right-click on the test method, e.g. testSomeMethodInClass in the example above, choose Run and testSomeMethodInClass. Take the one with the Android icon!

Now a dialog to choose device or emulator will most likely appear. Choose which one to run the test on.

Project structure

<Project>
+-.idea
+-gradle
+-<Module>
| +-build
| +-src
| | +-instrumentTest
| | | +-java
| | |   +-<package>.test
| | |     +-<ClassName>Test
| | +-main
| |   +-java
| |   | +-<package>
| |   |   +-<ClassName>
| |   +-res
| |   | +-drawable...
| |   | + ...
| |   | +-values...
| |   +-AndroidManifest.xml
| +-build.gradle  <<------------ THIS ONE!
+-build.gradle  <<-------------- *NOT* THIS ONE!