Android JUnit Test Example

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


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"?>
    package="" android:versionCode="1"
       <uses-library android:name="android.test.runner" />
    <uses-sdk android:minSdkVersion="3" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
       android:targetPackage="" android:label="Tests for My App" />

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


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();

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.


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


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!

Copyright © 2018 ProTech. All Rights Reserved.

Sign In Create Account


Social Media