Skip to content

Jumpstart on Android Unit Testing

ericwan78 edited this page Apr 28, 2013 · 7 revisions

Testing Android app without the aid of unit testing can be a repetitive, time consuming task. When we expect a specific behaviour in a piece of Java code, test cases can be created using JUnit. When a set of behaviours with expected outputs defined are translated into test code in a test project, all cases can be tested with a single run. It is a time efficient tool for spotting broken code and testing corner cases.

This documentation is created to help Tecla developers jumpstart on Android unit testing. The complete documentation can be found at Android Testing.

The Basics

If a piece of code can be tested without Android-specific components, a test class can inherit AndroidTestCase for testing. Use the following procedure as a general guideline in Eclipse to create a test project and write a test case:

To create an Android Test Project,

  1. Choose in the menu "File => New => Other ..."
  2. Select "Android => Android Test Project" and click Next
  3. Choose a project name (Usually the name of a test project uses the name of the application project with "Test" appended to it) and click Next
  4. Choose the project to be tested on and click next
  5. Choose the target SDK version and click Finish

A Test Case Example

Suppose the following method in com.example.helloworld.MyClass is to be tested,

public static int foo(int a, int b) {
    return a + b;
}

Assuming that a test project has been created, the following procedure can be used,

  1. Right click on the package com.example.helloworld.test and choose "New => Other ..."
  2. Select "Java => JUnit => JUnit Test Case and click Next
  3. Choose a class name (Usually the name of a test class uses the name of the application project class with "Test" appended to it) and click Finish
  4. Change class inheritance to AndroidTestCase and import android.test.AndroidTestCase
  5. Add test cases by writing the following methods in the class. For the purpose of demonstration here, the first test case assumes that foo returns the sum of two inputs and the second test case assumes that foo returns the difference between the two inputs
public void testFoo1() {
	int c = 5, d = 4, expected = 9, actual;
	actual = MyClass.add(c, d);
	this.assertEquals(expected, actual);
}
	
public void testFoo2() {
	int c = 5, d = 4, expected = 1, actual;
	actual = MyClass.add(c, d);
	this.assertEquals(expected, actual);
}

Running the Test

Right click on the test project and choose "Run As => Android JUnit Test". After running the test, the JUnit view s=will show the results. Following the example above, the results should show that one test case passed and one test case failed.

Activity Testing

Service Testing

Clone this wiki locally