Setting up an Android test application in IntelliJ

This may not be the best approach, but I figured I’d document the process that I go through, especially because it turns out there’s some hidden gotcha’s that took a bit of sleuthing to figure out.

1:  Fire up IntelliJ and select New Project from the File menu.  For there, select Android from the list on the left, and “Application Module” from the list on the right.

newProjectI would rather not create an application simply for testing, but this is the only option that allows you to select the target device (emulator or actual device.)

2: Click on Next and fill in the application, package, and activity name:

appName3: Click on Next and fill in the project name, select the project SDK, and select the target device.  These need to be configured for your own requirements regarding which SDK to use and how you are working with Android (emulation or actual device):

projectInfo4: Click on Finish.

5: If you haven’t done so, and you’re using an actual Android device, connect it and wait for the “AutoPlay” dialog to appear.  I learned that this may take a while — under a minute, but still I learned that you have to wait for this to happen before the IntelliJ will talk to the device.  Once the AutoPlay dialog appears, close it.

6: Right-click on the project and select New -> Module:

newModule7: Select “Test Module”:

newModule28: Click on Next and enter a module name:

newModule39: Click on Finish.  IntelliJ creates a “BlankActivityTest” file.  Delete this file:

deleteActivityTest10: Right click on the package under “src” and add a new Java class.  Provide a class name:

testClassName11: Start writing tests!

Easier said than done.  First off, you’ll need at least the following import;

import android.test.InstrumentationTestCase;

Next, you want to change your class so that it extends InstrumentationTestCase:

public class Tester extends InstrumentationTestCase {
    public Tester() {
        super();
    }

You can add setUp and tearDown processes as well:

    protected void setUp() throws Exception {
        super.setUp();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

Note that these functions must declare that they “throw Exception”

Finally, you can write some tests.  Tests must being with the word “test”!

    public void test1() {
        assertEquals(1, 1);
    }

    public void test2() {
        assertEquals(1, 2);
    }

That’s it!  Happy unit testing on Android using the IntelliJ IDE.

 

 

Advertisements