Thursday 25 August 2011


 


Using Ant to Automate Building Android Applications

 

The standard way to develop and deploy Android applications is using Eclipse. This is great because it is free, easy to use, and many Java developers already use Eclipse. To deploy your applications using Eclipse, you simply right-click on the on the project, choose to export the application, and follow the prompts

There are a few things we cannot easily do with this system, though. Using the Eclipse GUI does not allow one to easily:

  • Add custom build steps.
  • Use an automated build system.
  • Use build configurations.
  • Build the release project with one command.
Fortunately, the Android SDK comes equipped with support for Ant, which is a common build script system popular among Java developers. It is how you can develop Android applications without using Eclipse, if you so desire. This tutorial will show you how to incorporate an Ant build script into your Android projects (even if you still develop with Eclipse), create your release package ready for Marketplace deployment in one step, create a build configuration using a properties file, and alter your source files based on the configuration.

You can use the Ant build script to solve all of the problems listed above.  This tutorial expects you to already have your Android SDK setup correctly, and to have Ant installed.  It will also help to know a little about Ant if you want to add custom build steps, but you don't really need to know anything to follow the tutorial here.

Although I don't personally use an automated build system for my projects, I do use it to create configuration files and to run custom build scripts. I also believe that it is very important to have a one-step build system, which means that there is only one command to create your final release package (I'll explain why later). You can already run your application in debug mode with Eclipse with one step, but I feel it is important to be able to create the release package in one step as well.

Finally, if this is too much reading for your taste, you can jump straight into the summary for a few simple steps, and download the sample application at the end of the tutorial.

Ant in a nutshell

A build script in Ant is an XML file.  The default filename for a Ant build file isbuild.xml. Build steps in Ant are called tasks, which are defined by targets in the build file. When you build your Android application with the default build script, you would type ant release at the command line. In this case, Ant looks for the default filename build.xml, and release is the target which it builds. Therelease target builds the application ready for release (as opposed to for debugging). Another example would be ant clean, which cleans the project binaries.

You can do pretty much anything you can imagine with more custom build scripts, from copying files to making network calls. More detail about how to use Ant is beyond the scope of this tutorial, but I will show you some useful tricks.

One custom script which I enjoy very much uses ProGuard to obfuscate and shrink the code. I see the code size of my applications drop by a whopping 50% using it. It helps for users who may think your application is taking too much space on their device. I'll explain how to do this in a future tutorial.

Adding build.xml to an existing project

If you already have a project that you'd like to add the Ant build script to, then there is an easy command line tool you can use. Open up a command prompt and navigate to the base directory of your project. From there, use the command:
android update project --path .

Here is an example of successful output:

>android update project --path .
Updated local.properties

Added file C:\dev\blog\antbuild\build.xml

If the android command is not found, then you need to update your path to include the Android tools.  On Windows, you can use something like set path=%PATH%;C:\dev\android-sdk-windows\tools (substituting your actual Android installation directory), or even better add it to your path persistently by updating the environment variables through your system properties.

Now you will have a working ant build script in build.xml.  You can test your setup by typing ant at the command prompt, and you should receive something similar to the following boilerplate help:

>ant
Buildfile: C:\dev\blog\antbuild\build.xml
    [setup] Android SDK Tools Revision 6
    [setup] Project Target: Android 1.5
    [setup] API level: 3
    [setup] WARNING: No minSdkVersion value set. Application will install on all Android versions.
    [setup] Importing rules file: platforms\android-3\ant\ant_rules_r2.xml

help:
     [echo] Android Ant Build. Available targets:
     [echo]    help:      Displays this help.
     [echo]    clean:     Removes output files created by other targets.
     [echo]    compile:   Compiles project's .java files into .class files.
     [echo]    debug:     Builds the application and signs it with a debug key.
     [echo]    release:   Builds the application. The generated apk file must be
     [echo]               signed before it is published.
     [echo]    install:   Installs/reinstalls the debug package onto a running
     [echo]               emulator or device.
     [echo]               If the application was previously installed, the
     [echo]               signatures must match.
     [echo]    uninstall: Uninstalls the application from a running emulator or
     [echo]               device.

BUILD SUCCESSFUL

If the ant command is not found, then you need to update your path. Like above, on Windows use set path=%PATH%;C:\dev\apache-ant-1.8.1\bin (substituting your actual Ant installation directory), or even better update your environment variables.

At this point you should be able to type ant release at the command prompt, which will build the project, placing the unsigned .apk file inside of the bin/directory.

Note that the output from Ant will show further instructions under -release-nosign: which says to sign the apk manually and to run zipalign.  We'll get to these steps later in the signing section below.

Creating a new project with build.xml

If you've already created your project and followed the above instructions, you can skip this section. If not, you can may either create a new Android project using the regular Eclipse method (via New > Other... > Android Project), and follow the instructions in the above section, or you can use the command line as described here.

android create project --name YourProjectName --path C:\dev\YourProject --target android-3 --package com.company.testproject --activity MainActivity

Here is an example of successful output:

>android create project --name YourTestProject --path c:\temp\TestProject --target android-3 --package com.company.testproject --activity MainActivity

Created project directory: c:\temp\TestProject
Created directory C:\temp\TestProject\src\com\company\testproject
Added file c:\temp\TestProject\src\com\company\testproject\MainActivity.java
Created directory C:\temp\TestProject\res
Created directory C:\temp\TestProject\bin
Created directory C:\temp\TestProject\libs
Created directory C:\temp\TestProject\res\values
Added file c:\temp\TestProject\res\values\strings.xml
Created directory C:\temp\TestProject\res\layout
Added file c:\temp\TestProject\res\layout\main.xml
Added file c:\temp\TestProject\AndroidManifest.xml
Added file c:\temp\TestProject\build.xml

Note: To see the available targets, use android list target and you should see something like:

>android list target
id: 1 or "android-3"
     Name: Android 1.5
     Type: Platform
     API level: 3
     Revision: 4

     Skins: HVGA (default), HVGA-L, HVGA-P, QVGA-L, QVGA-P
In the above case, you can use either 1 or android-3 as the target ID.  In the sample project, I chose android-4, which corresponds to Android 1.6.

Once the project is created, you can test if your project build is setup correctly by typing ant at the command line.  See the above section for further instructions.

Synchronizing with Eclipse

If you open the Ant build script, build.xml, in Eclipse, you will see an error on the second line of the file at this line: <project name="MainActivity" default="help">.  The problem with this line is that it is saying that the default Ant target is "help", but the actual Ant targets used in the build file are imported from another location, which the Eclipse editor does not recognize. The import is done at the line <taskdef name="setup", which imports Ant files from the Android SDK.

Unfortunately, while this error is active in your project, you cannot debug your project from Eclipse, even though the Ant build.xml is not needed. There are two solutions. You can remove default="help" from the file, which will remove the error in Eclipse. If you do this, and type ant at a command prompt without any targets (as opposed to "ant release"), you won't get the default help.  Or, you can copy the imported Ant files directly into your code, which is exactly what you must do if you would like to customize your build. If you follow this tutorial, you won't have to worry about this error. See the Customizing the build section for more information.

Automatically signing your application

Before an application can be delivered to a device, the package must be signed. When debugging using Eclipse, the package is technically signed with a debugging key. (Alternatively, you can build a debug package using ant debug) For actual applications delivered to the Android Marketplace, you need to sign them with a real key. It is useful to put this step into the build process. On top of the ease of automating the process, it allows you to build your application in one step. (One-step builds are a Good IdeaTM)

If you have not already created a key, you can do so automatically using Eclipse (Right click project > Android Tools > Export Signed Application Package...), or follow the instructions here.

Now we must tell the build script about our keystore. Create a file calledbuild.properties in your project's base directory (in the same directory asbuild.xml and the other properties files), if it does not already exist. Add the following lines:

key.store=keystore
key.alias=www.androidengineer.com

Where keystore is the name of your keystore file and change the value ofkey.alias to your keystore's alias. Now when you run ant release, you will be prompted for your passwords, and the build will automatically sign and zipalign your package.

Of course, having to enter your password doesn't make for a one-step build process. So you could not use this for an automated build machine, for one thing. It also has the disadvantage of requiring you to type the password, which it will display clearly on the screen, which may be a security issue in some circumstances.  We can put the passwords into build.properties as well, which will solve the issue:

key.store.password=password
key.alias.password=password

Caution: There can be several issues with storing the keystore and passwords. Depending on your organization's security policies, you may not be able to store the passwords in version control, or you may not be able to give out the information to all developers who have access to the source. If you want to check in the keystore and the build.properties file, but not the passwords, you can create a separate properties file which could only be allowed on certain machines but not checked in to version control. For example, you could create asecure.properties file which goes on the build machine, but not checked in to version control so all developers wouldn't have access to it; import the extra properties file by adding <property file="secure.properties" /> tobuild.xml. Finally, you could always build the APKs unsigned with ant releaseby not adding any information to the properties files.  The package built using this method will need to be signed and aligned.

Customizing the build

Now that we've got a working Ant build script, we can create a one-step build. But if we want to customize the build further, we'll have to do a few extra steps. You can do anything with your build that you can do with Ant. There are a few things we'll have to do first.

The Ant targets are actually located in the Android SDK.  The targets are what you type after ant on the command line, such as release, clean, etc.  To customize the build further, we need to copy the imported targets into our own build file.

If you look in build.xml, you can see the instructions for how to customize your build steps:

The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
  - copy the content of the main node <project> from android_rules.xml
  - paste it in this build.xml below the <setup /> task.
  - disable the import by changing the setup task below to <setup import="false" />

Find the android_rules.xml file in your Android SDK. For example, mine is located at C:\dev\android-sdk-windows\platforms\android-4\templates. There, copy almost the entire file, excluding the project node (copy below<project name="MainActivity"> to above </project>), and paste it in yourbuild.xml file. Also, change the line <setup /> to <setup import="false"/>.

Now you can change around the build as you please. Test that the build file is still working properly by running a build.  For an example of what you can do with the custom build script, see the next section.

Using a Java configuration file

This is a great way to use a build property to affect the source code of your Android application. Imagine a configuration class in your project which sets some variables, such as a debugging flag or a URL string. You probably have a different set of these values when developing than when you release your application. For example, you may turn the logging flag off, or change the URL from a debugging server to a production server.

public class Config
{
    
/** Whether or not to include logging statements in the application. */
    
public final static boolean LOGGING = true;
}

It would be nice to have the above LOGGING flag be set from your build. That way, you can be sure that when you create your release package, all of the code you used for debugging won't be included. For example, you may have debugging log statements like this:

if (Config.LOGGING)
{
    
Log.d(TAG"[onCreate] Success");
}

You will probably want to leave these statements on during development, but remove them at release.  In fact, it is good practice to leave logging statements in your source code. It helps with later maintenance when you, and especially others, need to know how your code works. On the other hand, it is bad practice for an application to litter the Android log with your debugging statements. Using these configuration variables allows you to turn the logging on and off, while still leaving the source code intact.

Another great advantage of using this method of logging is that the bytecode contained within the logging statement can be completely removed by a Java bytecode shrinker such as ProGuard, which can be integrated into your build script.  I'll discuss how to do this in a later blog post.

A nice way to set the Config.LOGGING flag is in your build properties.  Add the following to build.properties:

# Turn on or off logging.
config.logging=true

To have this build property be incorporated into our source code, I will use the Ant type filterset with the copy task. What we can do is create a Java template file which has tokens such as @CONFIG.LOGGING@ and copy it to our source directory, replacing the tokens with whatever the build properties values are.  For example, in the sample application I have a file called Config.java in the config/ directory.

public class Config
{
    
/** Whether or not to include logging statements in the application. */
    
public final static boolean LOGGING = @CONFIG.LOGGING@;
}

Please note that this is not a source file, and that config/Config.java is notthe actual file used when compiling the project. The filesrc/com/yourpackage/Config.java, which is the copied file destination, is what will be used as a source file.

Now I will alter the build file to copy the template file to the source path, but replace @CONFIG.LOGGING with the value of the property config.logging, which is true. I will create an Ant target called config which will copy the above template to the source directory. This will be called before the compile target.

    <!-- Copy Config.java to our source tree, replacing custom tokens with values in build.properties. The configuration depends on "clean" because otherwise the build system will not detect changes in the configuration. -->
<target name="config">

<property name="config-target-path" value="${source.dir}/com/androidengineer/antbuild"/>

<!-- Copy the configuration file, replacing tokens in the file. -->
<copy file="config/Config.java" todir="${config-target-path}"
      overwrite="true" encoding="utf-8">
<filterset>
<filter token="CONFIG.LOGGING" value="${config.logging}"/>
</filterset>
</copy>

<!-- Now set it to read-only, as we don't want people accidentally
     editing the wrong one. NOTE: This step is unnecessary, but I do
     it so the developers remember that this is not the original file. -->
<chmod file="${config-target-path}/Config.java" perm="-w"/>
<attrib file="${config-target-path}/Config.java" readonly="true"/>

</target>

To make this Ant target execute before the compile target, we simply addconfig to the dependency of compile<target name="compile" depends="config, -resource-src, -aidl". We also make the config target call clean, because otherwise the build system will not detect changes in the configuration, and may not recompile the proper classes.

Note: The above Ant task sets the target file (in your source directory) to read-only.  This is not necessary, but I add it as a precaution to remind me that it is not the original file that I need to edit.  When developing, I will change the configuration sometimes without using the build, and Eclipse will automatically change the file from read-only for me.  I also do not check in the target file into version control; only the original template and build.properties.

Version control

Do not check in the local.properties file which is generated by the Android build tools. This is noted in the file itself; it sets paths based on the local machine. Do check in the default.properties file, which is used by the Android tools, and build.properties, which is the file which you edit to customize your project's build.

I also don't check in the target Config.java in the source directory, nor anything else is configured by the build. I don't want local changes to propagate to other developers, so I only check in the original template file in the config/ directory.

In my projects, when I release a new version of a project I always check in the properties file and tag it in the source repository with a tag name such as "VERSION_2.0". That way we are certain of what properties the application was built with, and we can reproduce the application exactly as it was released, if we later need to.

Summary

1. At the command line run android create project, or android update project in your project base directory if it already exists.
2. (Optional) Add key.store and key.alias to build.properties if you want to include the signing step in your build.
3. (Optional) Add key.store.password and key.alias.password tobuild.properties if you want to include the keystore passwords, to make the build run without any further input needed.
4. (Optional) If you would like to further customize the build, copy the SDK Ant build code from <SDK>/platforms/<target_platform>/templates/android_rules.xmlto your local build.xml and change <setup /> to <setup import="false"/>.
5. Use ant release to build your project. It will create the package in bin/.

Sample Application

The sample application is a simple Hello World application, but it also includes the custom build script as described in this tutorial.  It also includes the Config.java which is configurable by the build. First, you must run "android update project -p ." from the command line in the project's directory to let the tools set the SDK path in local.properties. Then you can turn on and off logging by changing the value of config.logging in build.properties. Finally, run ant release to build the application, which will create the signedbin/MainActivity-release.apk file ready to be released.

Project source code - antbuild.zip (13.4 Kb)

Wednesday 17 August 2011

Android unitTesting


In this tutorial, you will learn how to use Eclipse to create an Android JUnit Test Project, create automated unit tests and run them under a variety of conditions.

Before You Begin

The authors are assuming the reader has some basic knowledge of Android and have all of the tools such as Eclipse and the Android SDK installed and working. The examples given here are engineered to show how the Android JUnit framework can be used to test Android applications. Specifically, this tutorial will show you how to test aspects of an Activity and identify program errors. These errors are determined, but not addressed, as part of this tutorial.
Note: The code for the SimpleCalc application is available on Google Code as well as from the above link.

Step 1: Review the SimpleCalc Application

First, let’s take a few moments to look over the SimpleCalc application. It’s a very simple application with just one screen. The screen has two simple functions: it allows the user to input two values, adds or multiplies these values together and displays the result as shown below.
Junit Testing The SimpleCalc application

Step 2: Review the SimpleCalc Screen Layout

The SimpleCalc application has just one screen, so we have only one layout resource file called /res/layout/main.xml.
Here is a listing of the main.xml layout resource:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <TextView android:layout_width="fill_parent"  
  6.         android:layout_height="wrap_content" android:text="@string/hello"  
  7.         android:gravity="center_horizontal" android:textSize="48px"  
  8.         android:padding="12px" />  
  9.     <EditText android:layout_height="wrap_content" android:id="@+id/value1"  
  10.         android:hint="@string/hint1" android:inputType="numberDecimal"  
  11.         android:layout_width="fill_parent" android:textSize="48px"></EditText>  
  12.     <EditText android:layout_height="wrap_content" android:id="@+id/value2"  
  13.         android:hint="@string/hint2" android:inputType="numberDecimal"  
  14.         android:layout_width="fill_parent" android:textSize="48px"></EditText>  
  15.     <FrameLayout android:id="@+id/FrameLayout01"  
  16.         android:layout_width="wrap_content" android:layout_height="wrap_content"  
  17.         android:padding="12px" android:background="#ff0000">  
  18.         <LinearLayout android:id="@+id/LinearLayout02"  
  19.             android:layout_width="wrap_content" android:layout_height="wrap_content"  
  20.             android:orientation="horizontal" android:background="#000000"  
  21.             android:padding="4px">  
  22.             <TextView android:layout_width="wrap_content"  
  23.                 android:layout_height="wrap_content" android:text="@string/resultLabel"  
  24.                 android:textSize="48px" android:id="@+id/resultLabel"></TextView>  
  25.             <TextView android:layout_width="wrap_content"  
  26.                 android:layout_height="wrap_content" android:id="@+id/result"  
  27.                 android:textSize="48px" android:textStyle="bold"  
  28.                 android:layout_marginLeft="16px"></TextView>  
  29.         </LinearLayout>  
  30.     </FrameLayout>  
  31.     <LinearLayout android:id="@+id/LinearLayout03"  
  32.         android:layout_height="wrap_content" android:layout_width="fill_parent">  
  33.         <Button android:layout_height="wrap_content" android:id="@+id/addValues"  
  34.             android:text="@string/add" android:textSize="32px"  
  35.             android:layout_width="wrap_content"></Button>  
  36.         <Button android:layout_height="wrap_content" android:id="@+id/multiplyValues"  
  37.             android:text="@string/multiply" android:textSize="32px"  
  38.             android:layout_width="wrap_content"></Button>  
  39.     </LinearLayout>  
  40. </LinearLayout>  
This layout is fairly straightforward. The entire content of the screen is stored within a LinearLayout, allowing the controls to display one after another vertically. Within this parent layout, we have the following controls:
  • A TextView control displaying the header “Unit Testing Sample.”
  • Two EditText controls to collect user input in the form of two numbers.
  • A FrameLayout control which contains a horizontal LinearLayout with the result label TextView and resulting sum or product TextView. The FrameLayout displays a red border around these controls, highlighting the result.
  • Finally, another horizontal LinearLayout with two child controls: a Button control for addition and a Button control for multiplication.
This layout is designed to look right in the Android Layout Designer when the Nexus One option (which has a screen size of 800×480) is chosen in both portrait and landscape modes. You’ll soon see that this is not a bullet-proof way of designing layouts. As with the code you’ll see in the next step, it isn’t designed to work perfectly.

Step 3: Review the SimpleCalc Activity

The SimpleCalc application has just one screen, so we have only one Activity as well: MainActivity.java. The MainActivity.java class controls the behavior of the one screen, whose user interface is dictated by the main.xml layout.
Here is a listing of the MainActivity.java class:
  1. package com.mamlambo.article.simplecalc;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.TextView;  
  11.   
  12. public class MainActivity extends Activity {  
  13.    /** Called when the activity is first created. */  
  14.    @Override  
  15.    public void onCreate(Bundle savedInstanceState) {  
  16.        final String LOG_TAG = "MainScreen";  
  17.        super.onCreate(savedInstanceState);  
  18.        setContentView(R.layout.main);  
  19.   
  20.        final EditText value1 = (EditText) findViewById(R.id.value1);  
  21.        final EditText value2 = (EditText) findViewById(R.id.value2);  
  22.   
  23.        final TextView result = (TextView) findViewById(R.id.result);  
  24.   
  25.        Button addButton = (Button) findViewById(R.id.addValues);  
  26.        addButton.setOnClickListener(new OnClickListener() {  
  27.   
  28.            public void onClick(View v) {  
  29.                try {  
  30.                    int val1 = Integer.parseInt(value1.getText().toString());  
  31.                    int val2 = Integer.parseInt(value2.getText().toString());  
  32.   
  33.                    Integer answer = val1 + val2;  
  34.                    result.setText(answer.toString());  
  35.                } catch (Exception e) {  
  36.                    Log.e(LOG_TAG, "Failed to add numbers", e);  
  37.                }  
  38.            }  
  39.        });  
  40.   
  41.        Button multiplyButton = (Button) findViewById(R.id.multiplyValues);  
  42.        multiplyButton.setOnClickListener(new OnClickListener() {  
  43.   
  44.            public void onClick(View v) {  
  45.                try {  
  46.                    int val1 = Integer.parseInt(value1.getText().toString());  
  47.                    int val2 = Integer.parseInt(value2.getText().toString());  
  48.   
  49.                    Integer answer = val1 * val2;  
  50.                    result.setText(answer.toString());  
  51.                } catch (Exception e) {  
  52.                    Log.e(LOG_TAG, "Failed to multiply numbers", e);  
  53.                }  
  54.            }  
  55.        });  
  56.    }  
  57. }  

As you can see, the Java for this class is quite straightforward. It simply implements onClick() handlers for both the addition and multiplication Button controls.
When a Button is pressed, the Activity retrieves the values stored in the two EditText controls, calculates the result, and displays it in the TextView control called R.id.result.
Note: There are bugs in this code! These bugs have been designed specifically to illustrate unit testing.

Step 4: Creating an Android Test Project

You can add a test project to any Android project in two ways. You can add a test project while creating a new Android project with the Android Project Wizard or you can add a test project to an existing Android project. (The steps are basically the same.)
For this example, we have an existing project. To add a test project to the SimpleCalc project in Eclipse, take the following steps:
From the Project Explorer, choose the Android project you wish to add a test project to. Right-click on the project and choose Android Tools->New Test Project…
Junit Testing, Creating a Test Project

Step 5: Configuring the Android Test Project

Now you need to configure the test project settings, including the test project name, file location, Android project to test and build target (SDK version).
For this example, we can use the following settings:
  • Test project names generally end in “Test”, so let’s name this test project SimpleCalcTest
  • The project location can be wherever you normally store source files on your hard drive.
  • Choose the Android project to test: SimpleCalc
  • The appropriate build target will be selected automatically once you select the project to test. In this case, since the Android project is built for Android 2.1 + Google APIs (API Level 7), it makes sense to use the same build target for the test project.
  • It makes sense to name the test project accordingly: SimpleCalcTest, with the appropriate package name suffix simplecalc.test.
Configuring the project test
Hit Finish.

Step 6: Review the SimpleCalcTest Project

The SimpleCalcTest project is an Android project. You will notice that it has all the normal things you’d expect of an Android project, including a Manifest file and resources.
Junit Testing SimpleCalcTest Project Files

Step 7: Determine Unit Tests for the SimpleCalc Application

Now that you have a test project configured for the SimpleCalc application, it makes sense to determine some reasonable unit tests for the application.
Many software methodologies these days work compatibly with unit testing. Unit tests can greatly increase the stability and quality of your application and reduce testing costs. Unit tests come in many forms.
Unit tests can:
  • Improve testing coverage
  • Test application assumptions
  • Validate application functionality
Unit tests can be used to test core functionality, such as whether or not the SimpleCalc math is being performed correctly. They can also be used to verify if the user interface is displaying correctly. Now let’s look at some specific test cases.

Step 8: Create Your First Test Case

To create your first test case, right-click on the simplecalc.test package and choose New->JUnit Test Case.
Configuring test case settings.

Step 9: Configure Your First Test Case

Now you need to configure the test case settings.
For this example, we can use the following settings:
  • Both JUnit 3 and 4 are supported. We’ll use the default JUnit 3 here.
  • The source folder should be the location of the SimpleCalcTest project files.
  • The package should be the package name of the SimpleCalcTest project.
  • In this case, we will name the test case MathValidation.
  • For the SuperClass, choose "android.test.ActivityInstrumentationTestCase2." This is the test case you use for testing activities.
  • Check the boxes to add method stubs for setUp() and constructor.
junit Testing, Configuring test case settings.
Hit Finish. (You can safely ignore the warning saying, “Superclass does not exist.”)

Step 10: Review the MathValidation Test Case

The MathValidation.java test case source file is then created.
The lifecycle of a test case is basically this: construction, setUp(), tests run, tearDown(), and destruction. The setUp() method is used to do any general initialization used by all of specific tests. Each test to be run in the test case is implemented as its own method, where the method name begins with “test”. The tearDown() method is then used to uninitialize any resources acquired by the setUp() method.
  1. package com.mamlambo.article.simplecalc.test;  
  2.   
  3. import android.test.ActivityInstrumentationTestCase2;  
  4.   
  5. public class MathValidation extends  
  6.        ActivityInstrumentationTestCase2<MainActivity> {     
  7.   
  8.    public MathValidation(String name) {  
  9.        super(name);  
  10.    }  
  11.   
  12.    protected void setUp() throws Exception {  
  13.        super.setUp();  
  14.    }  
  15. }  
Now it’s time to implement the MathValidation Test Case

Step 11: Modify the MathValidation Class Constructor

First, modify the MathValidation class constructor. This constructor ties configures the internals of the Android test superclass we’re using.
  1. public MathValidation() {  
  2.        super("com.mamlambo.article.simplecalc", MainActivity.class);  
  3. }  

Step 12: Implement the MathValidation setUp() method

Now you need to gather the data required for validating the SimpleCalc math calculations. Begin by implementing the setUp() method. You can retrieve the Activity being tested using the getActivity() method as follows:
  1. MainActivity mainActivity = getActivity();  
Next, you need to retrieve an instance of the TextView control called R.id.result. This is the control that will hold the resulting sum or product from the math calculations used by the application.
The full updated code listing (MathValidation.java) with these modifications is shown below:
  1. package com.mamlambo.article.simplecalc.test;  
  2.   
  3. import android.test.ActivityInstrumentationTestCase2;  
  4. import android.widget.TextView;  
  5. import com.mamlambo.article.simplecalc.MainActivity;  
  6. import com.mamlambo.article.simplecalc.R;  
  7.   
  8. public class MathValidation extends ActivityInstrumentationTestCase2<MainActivity> {  
  9.   
  10.    private TextView result;  
  11.   
  12.    public MathValidation() {  
  13.        super ("com.mamlambo.article.simplecalc", MainActivity.class);  
  14.    }  
  15.   
  16.    @Override  
  17.    protected void setUp() throws Exception {  
  18.        super.setUp();  
  19.   
  20.        MainActivity mainActivity = getActivity();  
  21.   
  22.        result = (TextView) mainActivity.findViewById(R.id.result);  
  23.    }  
  24. }  

Step 13: Consider Tests for the SimpleCalc Application

Now that everything is set up, what tests do you want to perform? Let’s begin by checking the math used by the SimpleCalc application. Specifically, let’s check that the numbers are retrieved correctly, as well as added and multiplied correctly. Did we set the right types for our number values? Are we retrieving and performing mathematical calculations using the correct types?
To answer these questions, we must add some testing code to the MathValidation class. Each specific test will have it’s own method beginning with “test” – the “test” method name prefix is case sensitive! This naming scheme is how JUnit determines what methods to run.

Step 14: Implement a Method to Test SimpleCalc’s Addition

Let’s begin by testing the addition calculation of SimpleCalc. To do this, add a method called testAddValues() to the MathValidation class.
This test will enter two numbers (24 and 74) into the screen and press Enter, which acts as a click on the first Button control which is in focus. Then it will retrieve the sum displayed by the application in the result TextView control and test to see if the result is the expected one (98).
To supply the EditText controls with two numbers to sum, use the sendKeys() method. This method mimics how keys are sent to Android applications. If you use the setText() method of the EditText control to set the text in each control, then you are bypassing the validation of the numeric entry that user’s would encounter. This method of providing key strokes assumes that the focus starts on the first control and that using the Enter key goes to the next one (you’ll see that the enter key is sent at the end of each number). If neither of those assumptions is true, the test will also fail. This is not a bad thing, but it might be failing for the wrong reasons (e.g. focus or layout issues, rather than math issues).
Finally, you use the assertTrue() method to compare the actual result displayed on the screen to the expected result. ). We compare against a string, since the result is displayed as a string. This way, we can also make sure we don’t duplicate any math or type errors in the application logic within the test framework.
Here is the full listing of the testAddValues() method:
  1. private static final String NUMBER_24 = "2 4 ENTER ";  
  2. private static final String NUMBER_74 = "7 4 ENTER ";  
  3. private static final String ADD_RESULT = "98";  
  4.   
  5. public void testAddValues() {  
  6.   
  7.    sendKeys(NUMBER_24);  
  8.    // now on value2 entry  
  9.    sendKeys(NUMBER_74);  
  10.    // now on Add button  
  11.    sendKeys("ENTER");  
  12.   
  13.    // get result  
  14.    String mathResult = result.getText().toString();  
  15.    assertTrue("Add result should be 98", mathResult.equals(ADD_RESULT));  
  16. }  
Congratulations! You’ve created your first test!

Step 15: Enhancing the Tests for Addition

Now let’s add a few more tests to make sure all different types of numbers can be added, resulting in the display of the proper sum.
Because the activity is launched for each test, you do not need to clear the values or anything like that between tests. You also do not need to change the focus within the form, since it begins at value1. Therefore, you can simplify tests by concatenating key presses together in a single sendKeys() method call, like such:
  1. sendKeys(NUMBER_24 + NUMBER_74 + "ENTER");  
For example, here is the code for the testAddDecimalValues() method, which tests the addition of a decimal value 5.5 with the number 74, which should result in 79.5:
  1. public void testAddDecimalValues() {  
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + "ENTER");  
  3.   
  4.        String mathResult = result.getText().toString();  
  5.        assertTrue("Add result should be " + ADD_DECIMAL_RESULT + " but was "  
  6.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));  
  7.  }  

Similarly, you can perform a test of adding a negative number -22 to the number 74, which should result in a sum of 52. This test is implemented in the testSubtractValues() method, as follows:
  1. public void testAddDecimalValues() {  
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + "ENTER");  
  3.   
  4.        String mathResult = result.getText().toString();  
  5.        assertTrue("Add result should be " + ADD_DECIMAL_RESULT + " but was "  
  6.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));  
  7.    }  

Step 16: Implement a Method to Test SimpleCalc’s Multiplication

It should be quite straightforward to implement a similar test for SimpleCalc’s multiplication called testMuliplyValues().
The only tricky part is that the Multiply Button control is not in focus when we’re done entering the numbers (instead, the Add Button is).
You might think to just call the requestFocus() method on the multiply button. Unfortunately, this won’t work because requestFocus() has to be run on the UI thread in Android. Running methods on the UI Thread can be done as part of a test case, but it’s done asynchronously so you can’t guarantee when it will be complete.
Instead, we’ll again use the sendKeys() method. Since we defined the Multiply Button to always display to the right of the Add Button, we can just send the “DPAD_RIGHT” key followed by “ENTER” to click the Multiply Button.
  1. public void testMultiplyValues() {  
  2.    sendKeys(NUMBER_24+NUMBER_74+ " DPAD_RIGHT ENTER");  
  3.   
  4.    String mathResult = result.getText().toString();  
  5.    assertTrue("Multiply result should be " + MULTIPLY_RESULT + " but was "  
  6.            + mathResult, mathResult.equals(MULTIPLY_RESULT));  
  7. }  
As an exercise, you might try adding more multiplication tests with various sizes of numbers. Try to engineer a test that might fail with the existing code. Can you guess if each test will be successful or not? (Hint: Look at the type of the variable that the string is being converted to.)

Step 17: Running Unit Tests with the Android Emulator or Device

Unit test frameworks such as the one you’re building are Android applications like any other. They must be installed on the emulator or device you wish to test, along with the application to be tested (in this case, SimpleCalc).
To run the unit tests you have created so far from Eclipse, choose the Debug drop down, then Debug As, then Android JUnit Test. Make sure the file you just created is the active file (shown in the window) as that is the test case that will be launched.
junit testing, Debugging JUnit Test

Step 18: Examining the Test Results

The tests may take some time to complete, especially if the emulator was not already running. When the tests have completed, you should see results similar to those shown here:
Junit Testing Examining the Test Results
You’ll notice that all four of the tests you’ve just created run. Two of them are successful, while two of them have failed. Do you know why they’ve failed? (Fixing these calculation bugs is left as a learning exercise for the reader.)
Besides successful tests and failed tests, errors are also shown. A failure is when a tested for assertion fails. An error, on the other hand, is a thrown exception. Errors can either be untested for edge cases or simply mistakes in the testing code. If you have errors, check your testing code carefully to make sure it is working correctly.

Step 19: Create a Test Case for Screen Display Testing

Unit tests need not be limited to validating core functionality such as the addition and multiplication of values. Tests can also validate whether or not a screen layout is displayed properly.
For example, you might want to validate that all of the layout controls display properly on all target screens. The SimpleCalc’s screen was designed in the layout designer in Eclipse for an 800x480 screen in either landscape or portrait mode, but will it work on other screen sizes and devices? Were we then too specific in our design? Automated testing can tell us the answer to this question very quickly.
To create another test case, right-click on the SimpleCalc.Test package and choose New->JUnit Test Case. Call this new test LayoutTests. Configure this test case much as you did the MathValidation class in Step 8.
Junit testing, Create a Test Case for Screen Display Testing.
Hit Finish.

Step 20: Review and Update the LayoutTests Test Case

The LayoutTests.java test case source file is then created. Modify the class to look like the code listing below, modifying the constructor, retrieving the Button controls and the layout as a whole:
  1. package com.mamlambo.article.simplecalc.test;  
  2.   
  3. import android.test.ActivityInstrumentationTestCase2;  
  4. import android.view.View;  
  5. import android.widget.Button;  
  6.   
  7. import com.mamlambo.article.simplecalc.MainActivity;  
  8. import com.mamlambo.article.simplecalc.R;  
  9.   
  10. public class LayoutTests extends ActivityInstrumentationTestCase2<MainActivity> {  
  11.   
  12.    private Button addValues;  
  13.    private Button multiplyValues;  
  14.    private View mainLayout;  
  15.   
  16.    public LayoutTests() {  
  17.        super("com.mamlambo.article.simplecalc", MainActivity.class);  
  18.    }  
  19.   
  20.    protected void setUp() throws Exception {  
  21.        super.setUp();  
  22.   
  23.        MainActivity mainActivity = getActivity();  
  24.        addValues = (Button) mainActivity.findViewById(R.id.addValues);  
  25.        multiplyValues = (Button) mainActivity  
  26.                .findViewById(R.id.multiplyValues);  
  27.        mainLayout = (View) mainActivity.findViewById(R.id.mainLayout);  
  28.   
  29.    }  
  30. }  
Now let’s implement some specific tests for LayoutTests.
Step 20: Consider Layout Tests for the SimpleCalc Application
Now that everything is set up, what tests do you want to perform? One common bug in application design is for controls not to display properly in all screen sizes and orientations. Therefore, it makes sense to try to build a test case to verify the location of certain controls. You can then add other checks to make sure other View controls display and behave appropriately.

Step 21: Implement a Method to Test Button Display

Let’s begin by testing that the Add Button control of the SimpleCalc screen is visible. To do this, add a method called testAddButtonOnScreen() to the LayoutTests class.
This test checks to see if the Add Button control is displayed within the visible rectangle representing the overall screen size.
To implement the testAddButtonOnScreen() method, you must first determine the screen size. There are a number of ways to do this. One simple way is to retrieve the View that represents the entire screen layout and use the getWidth() and getHeight() methods. Doing this also takes in to account any screen real estate being used by other items, such as the title bar or information bar that are often at the top of an Android screen.
Determining whether or not the Add Button control is drawn within those bounds is as simple as comparing the layout bounds to the bounds of the drawing rectangle for the Add Button control.
Here is the full listing of the testAddButtonOnScreen() method:
  1. public void testAddButtonOnScreen() {  
  2.    int fullWidth = mainLayout.getWidth();  
  3.    int fullHeight = mainLayout.getHeight();  
  4.    int[] mainLayoutLocation = new int[2];  
  5.    mainLayout.getLocationOnScreen(mainLayoutLocation);  
  6.   
  7.    int[] viewLocation = new int[2];  
  8.    addValues.getLocationOnScreen(viewLocation);  
  9.   
  10.    Rect outRect = new Rect();  
  11.    addValues.getDrawingRect(outRect);  
  12.   
  13.    assertTrue("Add button off the right of the screen", fullWidth  
  14.            + mainLayoutLocation[0] > outRect.width() + viewLocation[0]);  
  15.   
  16.    assertTrue("Add button off the bottom of the screen", fullHeight  
  17.            + mainLayoutLocation[1] > outRect.height() + viewLocation[1]);  
  18. }  
At this point, you can see how you could also test the display of the Multiply Button, or the Result text, or any other control on the SimpleCalc screen.

Step 22: Running the LayoutTests Test Case

In order for layout testing to provide useful results, we can’t just run the test once. Instead, the tests must be run on multiple emulator configurations and screen orientations. This is different from the logic tests of above where a messy layout or a layout that doesn’t match the design pattern doesn’t necessarily impede functionality.
For example, if you create emulator configurations (using AVDs) for the following configurations, the LayoutTests test case will yield the following results:
  1. 480x800, portrait mode (will pass)
  2. 800x480, landscape mode (will fail)
  3. 320x480, portrait mode (will fail)
  4. 480x320, landscape (will fail)
  5. 480x854, portrait mode (will pass)
  6. 854x480, landscape mode (will fail)

 Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?
Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?
Hint: What’s shown on the screen when the application actually runs (see the figure below)?
JUnit Testing Sample

Step 23: Where to Go From Here

Now that you have some tests in place—some of which pass and some of which fail—you can imagine how unit testing can improve the quality of your application.
The more thorough you are with your unit testing coverage, the better. You’ve seen how unit testing can uncover bugs in code and layout designs. The next step would be to identify the failure points and fix those bugs. Once you’ve fixed the bugs, you should re-run the unit tests to ensure that they pass in all test cases.

Conclusion

In this tutorial, you learned how to create unit tests using the Android JUnit framework for your Android projects. You also learned how to create different kinds of unit tests to test a variety of application features, including underlying program functions as well as display characteristics.
We hope you enjoyed this tutorial and look forward to your feedback!