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

| +-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!


  1. Perfect!
    I was seeking for a small, objective and clear response to that. And finally here it is!

    Thank you very much, Nikolaj!

  2. Thanks for the guide. I had to make a minor modification to get it to work though:


    testPackage ".test"


    testPackageName ".test"

  3. when, i use testPackage ".test"
    or testPackageName ".test"
    i got error like this
    build script error unsupported gradle dsl method found

  4. Hi I tried this but I get an unsupported gradle dsl method found : instrumentTestCompile() error, can you please help me