Android JUnit Test Example

Android JUnit Test Example

Photo Max Walker
NewCircle, Inc.
Member since Sep 29, 2010
Stream Posts: 322
Posted on Jul 06, 2009 (6 years ago)
Seen 24154 times.
Tagged As:

Android ships with JUnit built in. But it's not the easiest to understand how to use it.

AndroidManifest.xml

Make sure you have specify that your application is using the junit libraries and remember to define the instrumentation.

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app.tests" android:versionCode="1"
    android:versionName="1.0">
    <application>
       <uses-library android:name="android.test.runner" />
    </application>
    <uses-sdk android:minSdkVersion="3" />
       
<instrumentation android:name="android.test.InstrumentationTestRunner"
       android:targetPackage="com.example.app" android:label="Tests for My App" />
</manifest>

AllTests.java

This is what kicks-start all the other tests. You can pretty much copy-paste this file into any of your projects.

package com.example.app;


import junit.framework.Test;
import junit.framework.TestSuite;
import android.test.suitebuilder.TestSuiteBuilder;


/**
 * A test suite containing all tests for my application.
 */
public class AllTests extends TestSuite {
    public static Test suite() {
        return new TestSuiteBuilder(AllTests.class).includeAllPackagesUnderHere().build();
    }
}

SomeTests.java

This is where you put your actual tests that will test your application. Remember that all methods need to start with 'test'. Use various assert methods to pass/fail the test case.

package com.example.app;


import junit.framework.Assert;
import android.test.AndroidTestCase;


public class SomeTest extends AndroidTestCase {

    public void testSomething() throws Throwable {
       Assert.assertTrue(1 + 1 == 2);
    }

    public void testSomethingElse() throws Throwable {
       Assert.assertTrue(1 + 1 == 3);
    }
}

Running Your Tests

Using Eclipse to Run JUnit Tests: Select the project, right-click and choose Run As...Android JUnit Test.

Or command line:
adb shell am instrument -w com.example.app.tests/android.test.InstrumentationTestRunner

Resuts

You should see the results in the JUnit view in Eclipse or on the command line, depending on how you ran it. That's it. Now go and write some unit tests!

Comments

You have to login to post a comment.
Posted on Mar 15, 2012 (3 years ago)
Member since Jun 26, 2011
Command line switch <-e class> could be used to execute a specific class - adb shell am instrument -w -e class com.example.app.SomeTest com.example.app.tests/android.test.InstrumentationTestRunner