diff --git a/docs/html/guide/developing/testing/index.jd b/docs/html/guide/developing/testing/index.jd index ea61cc362d785..2164705295384 100644 --- a/docs/html/guide/developing/testing/index.jd +++ b/docs/html/guide/developing/testing/index.jd @@ -1,6 +1,5 @@ page.title=Testing Overview @jd:body -

Android includes powerful tools for setting up and running test applications. Whether you are working in Eclipse with ADT or working from the command line, these tools @@ -9,7 +8,7 @@ page.title=Testing Overview

If you aren't yet familiar with the Android testing framework, please read the topic - Testing and Instrumentation + Testing Fundamentals before you get started. For a step-by-step introduction to Android testing, try the Hello, Testing diff --git a/docs/html/guide/developing/testing/testing_eclipse.jd b/docs/html/guide/developing/testing/testing_eclipse.jd index da1c0f0b531d9..3258af9b4306a 100644 --- a/docs/html/guide/developing/testing/testing_eclipse.jd +++ b/docs/html/guide/developing/testing/testing_eclipse.jd @@ -1,28 +1,23 @@ page.title=Testing In Eclipse, with ADT @jd:body -

-
-

In this document

-
    -
  1. Creating a Test Project
  2. -
  3. Creating a Test Application
  4. -
  5. Running Tests
  6. -
-
+
+

In this document

+
    +
  1. Creating a Test Project
  2. +
  3. Creating a Test Package
  4. +
  5. Running Tests
  6. +
+

- This topic explains how create and run tests of Android applications in Eclipse with ADT. - - with the basic processes for creating and running applications with ADT, as described in - Developing In Eclipse, with ADT. - - Before you read this topic, you should read about how to create a Android application with the - basic processes for creating and running applications with ADT, as described in - Developing In Eclipse, with ADT. - You may also want to read - Testing and Instrumentation, - which provides an overview of the Android testing framework. + This topic explains how create and run tests of Android applications in Eclipse with ADT. + Before you read this topic, you should read about how to create a Android application with the + basic processes for creating and running applications with ADT, as described in + Developing In Eclipse, with ADT. + You may also want to read + Testing Fundamentals, + which provides an overview of the Android testing framework.

ADT provides several features that help you set up and manage your testing environment @@ -32,20 +27,20 @@ page.title=Testing In Eclipse, with ADT

  • It lets you quickly create a test project and link it to the application under test. When it creates the test project, it automatically inserts the necessary - <instrumentation> element in the test application's manifest file. + <instrumentation> element in the test package's manifest file.
  • It lets you quickly import the classes of the application under test, so that your tests can inspect them.
  • - It lets you create run configurations for your test application and include in + It lets you create run configurations for your test package and include in them flags that are passed to the Android testing framework.
  • - It lets you run your test application without leaving Eclipse. ADT builds both the - application under test and the test application automatically, installs them if - necessary to your device or emulator, runs the test application, and displays the + It lets you run your test package without leaving Eclipse. ADT builds both the + application under test and the test package automatically, installs them if + necessary to your device or emulator, runs the test package, and displays the results in a separate window in Eclipse.
  • @@ -55,305 +50,396 @@ page.title=Testing In Eclipse, with ADT Testing in Other IDEs.

    Creating a Test Project

    -

    +

    To set up a test environment for your Android application, you must first create a separate - application project that holds the test code. The new project follows the directory structure + project that holds the test code. The new project follows the directory structure used for any Android application. It includes the same types of content and files, such as - source code, resources, a manifest file, and so forth. The test application you + source code, resources, a manifest file, and so forth. The test package you create is connected to the application under test by an <instrumentation> element in its manifest file. -

    -

    - The New Android Test Project dialog makes it easy for you to generate a - new test project that has the proper structure, including the - <instrumentation> element in the manifest file. You can use the New Android - Test Project dialog to generate the test project at any time. The dialog appears just after you - create a new Android main application project, but you can also run it to create a test project - for a project that you created previously. -

    +

    - To create a test project in Eclipse with ADT: + The New Android Test Project dialog makes it easy for you to generate a + new test project that has the proper structure, including the + <instrumentation> element in the manifest file. You can use the New + Android Test Project dialog to generate the test project at any time. The dialog appears + just after you create a new Android main application project, but you can also run it to + create a test project for a project that you created previously. +

    +

    + To create a test project in Eclipse with ADT:

      -
    1. - In Eclipse, select File > New > Other. This - opens the Select a Wizard dialog. -
    2. -
    3. - In the dialog, in the Wizards drop-down list, - find the entry for Android, then click the toggle to the left. Select - Android Test Project, then at the bottom - of the dialog click Next. The New Android Test Project wizard appears. -
    4. -
    5. - Enter a project name. You may use any name, but you may want to - associate the name with the project name for your Application. One - way to do this is to take the Application's project name, append the - string "Test" to it, and then use this as the test case project name. -
    6. -
    7. - In the Test Target panel, set - An Existing Android Project, click - Browse, then select your Android application from - the list. You now see that the wizard has completed the Test - Target Package, Application Name, and - Package Name fields for you (the latter two are in - the Properties panel). -
    8. -
    9. - In the Build Target panel, select the Android SDK - platform that you will use to test your application. Make this the same as the - build target of the application under test. -
    10. -
    11. - Click Finish to complete the wizard. If - Finish is disabled, look - for error messages at the top of the wizard dialog, and then fix - any problems. -
    12. +
    13. + In Eclipse, select File > New > Other. This opens the Select a + Wizard dialog. +
    14. +
    15. + In the dialog, in the Wizards drop-down list, find the entry for Android, then + click the toggle to the left. Select Android Test Project, then at the + bottom of the dialog click Next. The New Android Test Project + wizard appears. +
    16. +
    17. + Next to Test Project Name, enter a name for the project. You may use any name, + but you may want to associate the name with the project name for the application under test. + One way to do this is to take the application's project name, append the string "Test" to + it, and then use this as the test package project name. +

      + The name becomes part of the suggested project path, but you can change this in the + next step. +

      +
    18. +
    19. + In the Content panel, examine the suggested path to the project. + If Use default location is set, then the wizard will suggest a path that is + a concatenation of the workspace path and the project name you entered. For example, + if your workspace path is /usr/local/workspace and your project name is + MyTestApp, then the wizard will suggest + /usr/local/workspace/MyTestApp. To enter your own + choice for a path, unselect Use default location, then enter or browse to the + path where you want your project. +

      + To learn more about choosing the location of test projects, please read + + Testing Fundamentals. +

      +
    20. +
    21. + In the Test Target panel, set An Existing Android Project, click Browse, then select your + Android application from the list. You now see that the wizard has completed the Test + Target Package, Application Name, and Package Name fields for you (the latter two are in + the Properties panel). +
    22. +
    23. + In the Build Target panel, select the Android SDK platform that the application under test + uses. +
    24. +
    25. + Click Finish to complete the wizard. If Finish is disabled, look for error messages at the + top of the wizard dialog, and then fix any problems. +
    26. +
    +

    Creating a Test Package

    +

    + Once you have created a test project, you populate it with a test package. This package does not + require an Activity, although you can define one if you wish. Although your test package can + combine Activity classes, test case classes, or ordinary classes, your main test case + should extend one of the Android test case classes or JUnit classes, because these provide the + best testing features. +

    +

    + Test packages do not need to have an Android GUI. When you run the package in + Eclipse with ADT, its results appear in the JUnit view. Running tests and seeing the results is + described in more detail in the section Running Tests. +

    + +

    + To create a test package, start with one of Android's test case classes defined in + {@link android.test android.test}. These extend the JUnit + {@link junit.framework.TestCase TestCase} class. The Android test classes for Activity objects + also provide instrumentation for testing an Activity. To learn more about test case + classes, please read the topic + Testing Fundamentals. +

    +

    + Before you create your test package, you choose the Java package identifier you want to use + for your test case classes and the Android package name you want to use. To learn more + about this, please read + + Testing Fundamentals. +

    +

    + To add a test case class to your project: +

    +
      +
    1. + In the Project Explorer tab, open your test project, then open the src + folder. +
    2. +
    3. + Find the Java package identifier set by the projection creation wizard. If you haven't + added classes yet, this node won't have any children, and its icon will not be filled in. + If you want to change the identifier value, right-click the identifier and select + Refactor > Rename, then enter the new name. +
    4. +
    5. + When you are ready, right-click the Java package identifier again and select + New > Class. This displays the New Java Class + dialog, with the Source folder and Package values already set. +
    6. +
    7. + In the Name field, enter a name for the test case class. One way to choose a + class name is to append the string "Test" to the class of the component you are testing. + For example, if you are testing the class MyAppActivity, your test case class + name would be MyAppActivityTest. Leave the modifiers set to public. +
    8. +
    9. + In the Superclass field, enter the name of the Android test case class you + are extending. You can also browse the available classes. +
    10. +
    11. + In Which method stubs would you like to create?, unset all the options, then + click Finish. You will set up the constructor manually. +
    12. +
    13. + Your new class appears in a new Java editor pane. +

    - -

    -

    Creating a Test Application

    -

    - Once you have created a test project, you populate it with a test - Android application. This application does not require an {@link android.app.Activity Activity}, - although you can define one if you wish. Although your test application can - combine Activities, Android test class extensions, JUnit extensions, or - ordinary classes, you should extend one of the Android test classes or JUnit classes, - because these provide the best testing features. + You now have to ensure that the constructor is set up correctly. Create a constructor for your + class that has no arguments; this is required by JUnit. As the first statement in this + constructor, add a call to the base class' constructor. Each base test case class has its + own constructor signature. Refer to the class documentation in the documentation for + {@link android.test} for more information.

    - Test applications do not have an Android GUI. Instead, when you run the application in - Eclipse with ADT, its results appear in the JUnit view. If you run - your tests with {@link android.test.InstrumentationTestRunner InstrumentationTestRunner} (or a related test runner), - then it will run all the methods in each class. You can modify this behavior - by using the {@link junit.framework.TestSuite TestSuite} class. -

    - -

    - To create a test application, start with one of Android's test classes in the Java package {@link android.test android.test}. - These extend the JUnit {@link junit.framework.TestCase TestCase} class. With a few exceptions, the Android test classes - also provide instrumentation for testing. -

    -

    - For test classes that extend {@link junit.framework.TestCase TestCase}, you probably want to override - the setUp() and tearDown() methods: + To control your test environment, you will want to override the setUp() and + tearDown() methods:

    - Another useful convention is to add the method testPreConditions() to your test - class. Use this method to test that the application under test is initialized correctly. If this - test fails, you know that that the initial conditions were in error. When this happens, further test - results are suspect, regardless of whether or not the tests succeeded. + Another useful convention is to add the method testPreconditions() to your test + class. Use this method to test that the application under test is initialized correctly. If this + test fails, you know that that the initial conditions were in error. When this happens, further + test results are suspect, regardless of whether or not the tests succeeded.

    - The Resources tab contains an Activity Testing - tutorial with more information about creating test classes and methods. + The Resources tab contains an + Activity Testing + tutorial with more information about creating test classes and methods.

    Running Tests

    - - -

    Android includes a powerful set of testing tools that extend the -industry-standard JUnit test framework with features specific to the Android -environment. Although you can test an Android application with JUnit, the -Android tools allow you to write much more sophisticated tests for every aspect -of your application, both at the unit and framework levels.

    - -

    Key features of the Android testing environment include:

    - - - -

    This document is an overview of the Android testing environment and the way -you use it. The document assumes you have a basic knowledge of Android -application programming and JUnit testing methodology.

    - -

    Overview

    - -

    At the heart of the Android testing environment is an instrumentation -framework that your test application uses to precisely control the application -under test. With instrumentation, you can set up mock system objects such as -Contexts before the main application starts, control your application at various -points of its lifecycle, send UI events to the application, and examine the -application's state during its execution. The instrumentation framework -accomplishes this by running both the main application and the test application -in the same process.

    - -

    Your test application is linked to the application under test by means of an - - <instrumentation> element in the test application's manifest file. - The attributes of the element specify the package name of the application under test and also - tell Android how to run the test application. Instrumentation is described in more detail - in the section Instrumentation Test Runner. -

    - -

    The following diagram summarizes the Android testing environment:

    - - -

    - In Android, test applications are themselves Android applications, so you - write them in much the same way as the application you are testing. The SDK - tools help you create a main application project and its test project at the same - time. You can run Android tests within Eclipse with ADT or from the command - line. Eclipse with ADT provides an extensive set of tools for creating tests, - running them, and viewing their results. You can also use the adb - tool to run tests, or use a built-in Ant target. + The Android testing framework, an integral part of the development environment, + provides an architecture and powerful tools that help you test every aspect of your application + at every level from unit to framework. +

    +

    + The testing framework has these key features: +

    + +

    + This document describes the fundamentals of the Android testing framework, including the + structure of tests, the APIs that you use to develop tests, and the tools that you use to run + tests and view results. The document assumes you have a basic knowledge of Android application + programming and JUnit testing methodology. +

    +

    + The following diagram summarizes the testing framework: +

    +
    + + The Android testing framework + +
    +

    Test Structure

    +

    + Android's build and test tools assume that test projects are organized into a standard + structure of tests, test case classes, test packages, and test projects. +

    +

    + Android testing is based on JUnit. In general, a JUnit test is a method whose + statements test a part of the application under test. You organize test methods into classes + called test cases (or test suites). Each test is an isolated test of an individual module in + the application under test. Each class is a container for related test methods, although it + often provides helper methods as well. +

    +

    + In JUnit, you build one or more test source files into a class file. Similarly, in Android you + use the SDK's build tools to build one or more test source files into class files in an + Android test package. In JUnit, you use a test runner to execute test classes. In Android, you + use test tools to load the test package and the application under test, and the tools then + execute an Android-specific test runner. +

    +

    Test Projects

    +

    + Tests, like Android applications, are organized into projects. +

    +

    + A test project is a directory or Eclipse project in which you create the source code, manifest + file, and other files for a test package. The Android SDK contains tools for Eclipse with ADT + and for the command line that create and update test projects for you. The tools create the + directories you use for source code and resources and the manifest file for the test package. + The command-line tools also create the Ant build files you need. +

    +

    + You should always use Android tools to create a test project. Among other benefits, + the tools: +

    + +

    + You can create a test project anywhere in your file system, but the best approach is to + add the test project so that its root directory tests/ is at the same level + as the src/ directory of the main application's project. This helps you find the + tests associated with an application. For example, if your application project's root directory + is MyProject, then you should use the following directory structure: +

    +
    +  MyProject/
    +      AndroidManifest.xml
    +      res/
    +          ... (resources for main application)
    +      src/
    +          ... (source code for main application) ...
    +      tests/
    +          AndroidManifest.xml
    +          res/
    +              ... (resources for tests)
    +          src/
    +              ... (source code for tests)
    +
    +

    The Testing API

    +

    + The Android testing API is based on the JUnit API and extended with a instrumentation + framework and Android-specific testing classes. +

    +

    JUnit

    +

    + You can use the JUnit {@link junit.framework.TestCase TestCase} class to do unit testing on + a plain Java object. TestCase is also the base class for + {@link android.test.AndroidTestCase}, which you can use to test Android-dependent objects. + Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup, + teardown, and helper methods. +

    +

    + You use the JUnit {@link junit.framework.Assert} class to display test results. + The assert methods compare values you expect from a test to the actual results and + throw an exception if the comparison fails. Android also provides a class of assertions that + extend the possible types of comparisons, and another class of assertions for testing the UI. + These are described in more detail in the section + Assertion classes +

    +

    + To learn more about JUnit, you can read the documentation on the + junit.org home page. + Note that the Android testing API supports JUnit 3 code style, but not JUnit 4. Also, you must + use Android's instrumented test runner {@link android.test.InstrumentationTestRunner} to run + your test case classes. This test runner is described in the + section Running Tests. +

    +

    Instrumentation

    +

    + Android instrumentation is a set of control methods or "hooks" in the Android system. These hooks + control an Android component independently of its normal lifecycle. They also control how + Android loads applications. +

    +

    + Normally, an Android component runs in a lifecycle determined by the system. For example, an + Activity object's lifecycle starts when the Activity is activated by an Intent. The object's + onCreate() method is called, followed by onResume(). When the user + starts another application, the onPause() method is called. If the Activity + code calls the finish() method, the onDestroy() method is called. + The Android framework API does not provide a way for your code to invoke these callback + methods directly, but you can do so using instrumentation. +

    +

    + Also, the system runs all the components of an application into the same + process. You can allow some components, such as content providers, to run in a separate process, + but you can't force an application to run in the same process as another application that is + already running. +

    +

    + With Android instrumentation, though, you can invoke callback methods in your test code. + This allows you to run through the lifecycle of a component step by step, as if you were + debugging the component. The following test code snippet demonstrates how to use this to + test that an Activity saves and restores its state: +

    + +
    +    // Start the main activity of the application under test
    +    mActivity = getActivity();
    +
    +    // Get a handle to the Activity object's main UI widget, a Spinner
    +    mSpinner = (Spinner)mActivity.findViewById(com.android.example.spinner.R.id.Spinner01);
    +
    +    // Set the Spinner to a known position
    +    mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION);
    +
    +    // Stop the activity - The onDestroy() method should save the state of the Spinner
    +    mActivity.finish();
    +
    +    // Re-start the Activity - the onResume() method should restore the state of the Spinner
    +    mActivity = getActivity();
    +
    +    // Get the Spinner's current position
    +    int currentPosition = mActivity.getSpinnerPosition();
    +
    +    // Assert that the current position is the same as the starting position
    +    assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition);
    +
    +

    + The key method used here is + {@link android.test.ActivityInstrumentationTestCase2#getActivity()}, which is a + part of the instrumentation API. The Activity under test is not started until you call this + method. You can set up the test fixture in advance, and then call this method to start the + Activity. +

    +

    + Also, instrumentation can load both a test package and the application under test into the + same process. Since the application components and their tests are in the same process, the + tests can invoke methods in the components, and modify and examine fields in the components. +

    +

    Test case classes

    +

    + Android provides several test case classes that extend {@link junit.framework.TestCase} and + {@link junit.framework.Assert} with Android-specific setup, teardown, and helper methods. +

    +

    AndroidTestCase

    +

    + A useful general test case class, especially if you are + just starting out with Android testing, is {@link android.test.AndroidTestCase}. It extends + both {@link junit.framework.TestCase} and {@link junit.framework.Assert}. It provides the + JUnit-standard setUp() and tearDown() methods, as well as well as + all of JUnit's Assert methods. In addition, it provides methods for testing permissions, and a + method that guards against memory leaks by clearing out certain class references. +

    +

    Component-specific test cases

    +

    + A key feature of the Android testing framework is its component-specific test case classes. + These address specific component testing needs with methods for fixture setup and + teardown and component lifecycle control. They also provide methods for setting up mock objects. + These classes are described in the component-specific testing topics: +

    + +

    + Android does not provide a separate test case class for BroadcastReceiver. Instead, test a + BroadcastReceiver by testing the component that sends it Intent objects, to verify that the + BroadcastReceiver responds correctly. +

    +

    ApplicationTestCase

    +

    + You use the {@link android.test.ApplicationTestCase} test case class to test the setup and + teardown of {@link android.app.Application} objects. These objects maintain the global state of + information that applies to all the components in an application package. The test case can + be useful in verifying that the <application> element in the manifest file is correctly + set up. Note, however, that this test case does not allow you to control testing of the + components within your application package. +

    +

    InstrumentationTestCase

    +

    + If you want to use instrumentation methods in a test case class, you must use + {@link android.test.InstrumentationTestCase} or one of its subclasses. The + {@link android.app.Activity} test cases extend this base class with other functionality that + assists in Activity testing.

    +

    Assertion classes

    +

    + Because Android test case classes extend JUnit, you can use assertion methods to display the + results of tests. An assertion method compares an actual value returned by a test to an + expected value, and throws an AssertionException if the comparison test fails. Using assertions + is more convenient than doing logging, and provides better test performance. +

    +

    + Besides the JUnit {@link junit.framework.Assert} class methods, the testing API also provides + the {@link android.test.MoreAsserts} and {@link android.test.ViewAsserts} classes: +

    + +

    Mock object classes

    +

    + To facilitate dependency injection in testing, Android provides classes that create mock system + objects such as {@link android.content.Context} objects, + {@link android.content.ContentProvider} objects, {@link android.content.ContentResolver} + objects, and {@link android.app.Service} objects. Some test cases also provide mock + {@link android.content.Intent} objects. You use these mocks both to isolate tests + from the rest of the system and to facilitate dependency injection for testing. These classes + are found in the Java packages {@link android.test} and {@link android.test.mock}. +

    +

    + Mock objects isolate tests from a running system by stubbing out or overriding + normal operations. For example, a {@link android.test.mock.MockContentResolver} + replaces the normal resolver framework with its own local framework, which is isolated + from the rest of the system. MockContentResolver also also stubs out the + {@link android.content.ContentResolver#notifyChange(Uri, ContentObserver, boolean)} method + so that observer objects outside the test environment are not accidentally triggered. +

    +

    + Mock object classes also facilitate dependency injection by providing a subclass of the + normal object that is non-functional except for overrides you define. For example, the + {@link android.test.mock.MockResources} object provides a subclass of + {@link android.content.res.Resources} in which all the methods throw Exceptions when called. + To use it, you override only those methods that must provide information. +

    +

    + These are the mock object classes available in Android: +

    +

    Simple mock object classes

    +

    + {@link android.test.mock.MockApplication}, {@link android.test.mock.MockContext}, + {@link android.test.mock.MockContentProvider}, {@link android.test.mock.MockCursor}, + {@link android.test.mock.MockDialogInterface}, {@link android.test.mock.MockPackageManager}, and + {@link android.test.mock.MockResources} provide a simple and useful mock strategy. They are + stubbed-out versions of the corresponding system object class, and all of their methods throw an + {@link java.lang.UnsupportedOperationException} exception if called. To use them, you override + the methods you need in order to provide mock dependencies. +

    +

    Note: + {@link android.test.mock.MockContentProvider} + and {@link android.test.mock.MockCursor} are new as of API level 8. +

    +

    Resolver mock objects

    +

    + {@link android.test.mock.MockContentResolver} provides isolated testing of content providers by + masking out the normal system resolver framework. Instead of looking in the system to find a + content provider given an authority string, MockContentResolver uses its own internal table. You + must explicitly add providers to this table using + {@link android.test.mock.MockContentResolver#addProvider(String,ContentProvider)}. +

    +

    + With this feature, you can associate a mock content provider with an authority. You can create + an instance of a real provider but use test data in it. You can even set the provider for an + authority to null. In effect, a MockContentResolver object isolates your test + from providers that contain real data. You can control the + function of the provider, and you can prevent your test from affecting real data. +

    +

    Contexts for testing

    +

    + Android provides two Context classes that are useful for testing: +

    + +

    Running Tests

    +

    + Test cases are run by a test runner class that loads the test case class, set ups, + runs, and tears down each test. An Android test runner must also be instrumented, so that + the system utility for starting applications can control how the test package + loads test cases and the application under test. You tell the Android platform + which instrumented test runner to use by setting a value in the test package's manifest file. +

    +

    + {@link android.test.InstrumentationTestRunner} is the primary Android test runner class. It + extends the JUnit test runner framework and is also instrumented. It can run any of the test + case classes provided by Android and supports all possible types of testing. +

    +

    + You specify InstrumentationTestRunner or a subclass in your test package's + manifest file, in the + instrumentation element. Also, InstrumentationTestRunner code resides + in the shared library android.test.runner, which is not normally linked to + Android code. To include it, you must specify it in a + uses-library element. + You do not have to set up these elements yourself. Both Eclipse with ADT and the + android command-line tool construct them automatically and add them to your + test package's manifest file. +

    +

    + Note: If you use a test runner other than + InstrumentationTestRunner, you must change the <instrumentation> + element to point to the class you want to use. +

    +

    + To run {@link android.test.InstrumentationTestRunner}, you use internal system classes called by + Android tools. When you run a test in Eclipse with ADT, the classes are called automatically. + When you run a test from the command line, you run these classes with + Android Debug Bridge (adb). +

    +

    + The system classes load and start the test package, kill any processes that + are running an instance of the application under test, and then load a new instance of the + application under test. They then pass control to + {@link android.test.InstrumentationTestRunner}, which runs + each test case class in the test package. You can also control which test cases and + methods are run using settings in Eclipse with ADT, or using flags with the command-line tools. +

    +

    + Neither the system classes nor {@link android.test.InstrumentationTestRunner} run + the application under test. Instead, the test case does this directly. It either calls methods + in the application under test, or it calls its own methods that trigger lifecycle events in + the application under test. The application is under the complete control of the test case, + which allows it to set up the test environment (the test fixture) before running a test. This + is demonstrated in the previous code snippet that tests an + Activity that displays a Spinner widget. +

    +

    + To learn more about running tests, please read the topics + + Testing in Eclipse, with ADT or + + Testing in Other IDes. +

    +

    Seeing Test Results

    +

    + The Android testing framework returns test results back to the tool that started the test. + If you run a test in Eclipse with ADT, the results are displayed in a new JUnit view pane. If + you run a test from the command line, the results are displayed in STDOUT. In + both cases, you see a test summary that displays the name of each test case and method that + was run. You also see all the assertion failures that occurred. These include pointers to the + line in the test code where the failure occurred. Assertion failures also list the expected + value and actual value. +

    +

    + The test results have a format that is specific to the IDE that you are using. The test + results format for Eclipse with ADT is described in + + Testing in Eclipse, with ADT. The test results format for tests run from the + command line is described in + + Testing in Other IDEs. +

    +

    Monkey and MonkeyRunner

    +

    + The SDK provides two tools for functional-level application testing: +

    + +

    Working With Package names

    +

    + In the test environment, you work with both Android application package names and + Java package identifiers. Both use the same naming format, but they represent substantially + different entities. You need to know the difference to set up your tests correctly. +

    +

    + An Android package name is a unique system name for a .apk file, set by the + "android:package" attribute of the <manifest> element in the package's + manifest. The Android package name of your test package must be different from the + Android package name of the application under test. By default, Android tools create the + test package name by appending ".test" to the package name of the application under test. +

    +

    + The test package also uses an Android package name to target the application package it + tests. This is set in the "android:targetPackage" attribute of the + <instrumentation> element in the test package's manifest. +

    +

    + A Java package identifier applies to a source file. This package name reflects the directory + path of the source file. It also affects the visibility of classes and members to each other. +

    +

    + Android tools that create test projects set up an Android test package name for you. + From your input, the tools set up the test package name and the target package name for the + application under test. For these tools to work, the application project must already exist. +

    +

    + By default, these tools set the Java package identifier for the test class to be the same + as the Android package identifier. You may want to change this if you want to expose + members in the application under test by giving them package visibility. If you do this, + change only the Java package identifier, not the Android package names, and change only the + test case source files. Do not change the Java package name of the generated + R.java class in your test package, because it will then conflict with the + R.java class in the application under test. Do not change the Android package name + of your test package to be the same as the application it tests, because then their names + will no longer be unique in the system. +

    +

    What to Test

    +

    + The topic What To Test + describes the key functionality you should test in an Android application, and the key + situations that might affect that functionality. +

    +

    + Most unit testing is specific to the Android component you are testing. + The topics Activity Testing, + + Content Provider Testing, and + Service Testing each have a section entitled "What To Test" that lists possible testing + areas. +

    +

    + When possible, you should run these tests on an actual device. If this is not possible, you can + use the Android Emulator with + Android Virtual Devices configured for + the hardware, screens, and versions you want to test. +

    +

    Next Steps

    To learn how to set up and run tests in Eclipse, please refer to Testing in @@ -150,12 +627,10 @@ in the same process.

    href="{@docRoot}guide/developing/testing/testing_otheride.html">Testing in Other IDEs.

    -

    If you want a step-by-step introduction to Android testing, try one of the - testing tutorials: + testing tutorials or sample test packages:

    - -

    The Testing API

    -

    - For writing tests and test applications in the Java programming language, Android provides a - testing API that is based in part on the JUnit test framework. Adding to that, Android includes - a powerful instrumentation framework that lets your tests access the state and runtime objects - of the application under tests. -

    -

    - The sections below describe the major components of the testing API available in Android. -

    -

    JUnit test case classes

    -

    - Some of the classes in the testing API extend the JUnit {@link junit.framework.TestCase TestCase} - but do not use the instrumentation framework. These classes contain methods for accessing system - objects such as the Context of the application under test. With this Context, you can look at its - resources, files, databases, and so forth. The base class is {@link android.test.AndroidTestCase}, - but you usually use a subclass associated with a particular component. -

    - The subclasses are: -

    - -

    Instrumentation test case classes

    -

    - The API for testing activities extends the JUnit {@link junit.framework.TestCase TestCase} class - and also uses the instrumentation framework. With instrumentation, Android can automate UI - testing by sending events to the application under test, precisely control the start of an - activity, and monitor the state of the activity during its life cycle. -

    -

    - The base class is {@link android.test.InstrumentationTestCase}. All of its subclasses have - the ability to send a keystroke or touch event to the UI of the application - under test. The subclasses can also inject a mock Intent. The subclasses are: -

    - -

    Assert classes

    -

    - Android also extends the JUnit {@link junit.framework.Assert} class that is the basis of - assert() calls in tests. There are two extensions to this class, - {@link android.test.MoreAsserts} and {@link android.test.ViewAsserts}: -

    - -

    Mock object classes

    -

    - Android has convenience classes for creating mock system objects such as applications, contexts, - content resolvers, and resources. Android also provides methods in some test classes for - creating mock Intents. Use these mocks to facilitate dependency injection, since they are - easier to use than creating their real counterparts. These convenience classes are found in - {@link android.test} and {@link android.test.mock}. They are: -

    - -

    Instrumentation Test Runner

    -

    - Android provides a custom class for running tests with instrumentation called called - {@link android.test.InstrumentationTestRunner}. This class - controls of the application under test, runs the test application and the main application in the - same process, and routes test output to the appropriate place. Using instrumentation is key to the - ability of InstrumentationTestRunner to control the entire test - environment at runtime. Notice that you use this test runner even if your test class does not - itself use instrumentation. -

    -

    - When you run a test application, you first run a system utility called Activity Manager. Activity - Manager uses the instrumentation framework to start and control the test runner, which in turn - uses instrumentation to shut down any running instances of the main application, starts the test - application, and then starts the main application in the same process. This allows various - aspects of the test application to work directly with the main application. -

    -

    - If you are developing in Eclipse, the ADT plugin assists you in the setup of - InstrumentationTestRunner or other test runners. The plugin UI prompts you to specify - the test runner class to use, as well as the package name of the application under test. - The plugin then adds an <instrumentation> element with appropriate attributes - to the manifest file of the test application. Eclipse with ADT automatically starts a test - application under the control of Activity Manager using instrumentation, and redirects the test - output to the Eclipse window's JUnit view. -

    -

    - If you prefer working from the command line, you can use Ant and the android - tool to help you set up your test projects. To run tests with instrumentation, you can access the - Activity Manager through the Android Debug - Bridge (adb) tool and the output is directed to STDOUT. -

    -

    Working in the Test Environment

    -

    - The tests for an Android application are contained in a test application, which itself is an - Android application. A test application resides in a separate Android project that has the - same files and directories as a regular Android application. The test project is linked to the - project of the application it tests (known as the application under test) by its manifest file. -

    -

    - Each test application contains one or more test case classes based on an Android class for a - particular type of component. The test case class contains methods that define tests on some - part of the application under test. When you run the test application, Android - starts it, loads the application under test into the same process, and then invokes each method - in the test case class. -

    -

    - The tools and procedures you use with testing depend on the development environment you are - using. If you use Eclipse, then the ADT plug in for Eclipse provides tools that allow you to - develop and run tests entirely within Eclipse. This is documented in the topic - - Testing in Eclipse, with ADT. If you use another development environment, then you use - Android's command-line tools, as documented in the topic - Testing in Other IDEs. -

    -

    Working with test projects

    -

    - To start testing an Android application, you create a test project for it using Android tools. - The tools create the project directory and the files and subdirectories needed. - The tools also create a manifest file that links the application in the test project to the - application under test. The procedure for creating a test project in Eclipse with ADT is - documented in - Testing in Eclipse, with ADT. The procedure for creating a test project for use with - development tools other than Eclipse is documented in - Testing in Other IDEs. -

    -

    Working with test case classes

    -

    - A test application contains one or more test case classes that extend an Android test case - class. You choose a test case class based on the type of Android component you are testing and - the tests you are doing. A test application can test different components, but each test case - class is designed to test a single type of component. The Android test case classes are - described in the section The Testing API. -

    -

    - Some Android components have more than one associated test case class. In this case, you choose - among the available classes based on the type of tests you want to do. For activities, for - example, you have the choice of either {@link android.test.ActivityInstrumentationTestCase2} or - {@link android.test.ActivityUnitTestCase}. -

    - ActivityInstrumentationTestCase2 is designed to do functional testing, so it tests - activities in a normal system infrastructure. You can inject mocked Intents, but not - mocked Contexts. In general, you can't mock dependencies for the activity under test. -

    -

    - In comparison, ActivityUnitTestCase is designed for unit testing, so it tests - activities in an isolated system infrastructure. You can inject mocked or wrappered - dependencies for the activity under test, particularly mocked Contexts. On the other hand, - when you use this test case class the activity under test runs in isolation and can't interact - with other activities. -

    -

    - As a rule of thumb, if you wanted to test an activity's interaction with the rest of Android, - you would use ActivityInstrumentationTestCase2. If you wanted to do regression - testing on an activity, you would use ActivityUnitTestCase. -

    -

    Working with test methods

    -

    - Each test case class provides methods that you use to set up the test environment and control - the application under test. For example, all test case classes provide the JUnit - {@link junit.framework.TestCase#setUp() setUp()} method that you can override to set up - fixtures. In addition, you add methods to the class to define individual tests. Each method you - add is run once each time you run the test application. If you override the setUp() - method, it runs before each of your methods. Similarly, the JUnit - {@link junit.framework.TestCase#tearDown() tearDown()} method is run once after each of - your methods. -

    -

    - The test case classes give you substantial control over starting and stopping components. For - this reason, you have to specifically tell Android to start a component before you run tests - against it. For example, you use the - {@link android.test.ActivityInstrumentationTestCase2#getActivity()} method to start the activity - under test. You can call this method once during the entire test case, or once for each test - method. You can even destroy the activity under test by calling its - {@link android.app.Activity#finish()} method and then restart it with - getActivity() within a single test method. -

    -

    Running tests and seeing the results

    -

    - To run your tests, you build your test project and then run the test application using the - system utility Activity Manager with instrumentation. You provide to Activity Manager the name - of the test runner (usually {@link android.test.InstrumentationTestRunner}) you specified for - your application; the name includes both your test application's package name and the test - runner class name. Activity Manager loads and starts your test application, kills any instances - of the application under test, loads an instance of the application under test into the same - process as the test application, and then passes control to the first test case class in your - test application. The test runner then takes control of the tests, running each of your test - methods against the application under test until all the methods in all the classes have been - run. -

    -

    - If you run a test within Eclipse with ADT, the output appears in a new JUnit view pane. If you - run a test from the command line, the output goes to STDOUT. -

    -

    What to Test

    -

    - In addition to the functional areas you would normally test, here are some areas - of Android application testing that you should consider: -

    - -

    - When possible, you should run these tests on an actual device. If this is not possible, you can - use the Android Emulator with - Android Virtual Devices configured for - the hardware, screens, and versions you want to test. -

    -

    Appendix: UI Testing Notes

    -

    - The following sections have tips for testing the UI of your Android application, specifically - to help you handle actions that run in the UI thread, touch screen and keyboard events, and home - screen unlock during testing. -

    -

    Testing on the UI thread

    -

    - An application's activities run on the application's UI thread. Once the - UI is instantiated, for example in the activity's onCreate() method, then all - interactions with the UI must run in the UI thread. When you run the application normally, it - has access to the thread and does not have to do anything special. -

    -

    - This changes when you run tests against the application. With instrumentation-based classes, - you can invoke methods against the UI of the application under test. The other test classes - don't allow this. To run an entire test method on the UI thread, you can annotate the thread - with @UIThreadTest. Notice that this will run all of the method statements - on the UI thread. Methods that do not interact with the UI are not allowed; for example, you - can't invoke Instrumentation.waitForIdleSync(). -

    -

    - To run a subset of a test method on the UI thread, create an anonymous class of type - Runnable, put the statements you want in the run() method, and - instantiate a new instance of the class as a parameter to the method - appActivity.runOnUiThread(), where appActivity is - the instance of the app you are testing. -

    -

    - For example, this code instantiates an activity to test, requests focus (a UI action) for the - Spinner displayed by the activity, and then sends a key to it. Notice that the calls to - waitForIdleSync and sendKeys aren't allowed to run on the UI thread: -

    -
    -  private MyActivity mActivity; // MyActivity is the class name of the app under test
    -  private Spinner mSpinner;
    -
    -  ...
    -
    -  protected void setUp() throws Exception {
    -      super.setUp();
    -      mInstrumentation = getInstrumentation();
    -
    -      mActivity = getActivity(); // get a references to the app under test
    -
    -      /*
    -       * Get a reference to the main widget of the app under test, a Spinner
    -       */
    -      mSpinner = (Spinner) mActivity.findViewById(com.android.demo.myactivity.R.id.Spinner01);
    -
    -  ...
    -
    -  public void aTest() {
    -      /*
    -       * request focus for the Spinner, so that the test can send key events to it
    -       * This request must be run on the UI thread. To do this, use the runOnUiThread method
    -       * and pass it a Runnable that contains a call to requestFocus on the Spinner.
    -       */
    -      mActivity.runOnUiThread(new Runnable() {
    -          public void run() {
    -              mSpinner.requestFocus();
    -          }
    -      });
    -
    -      mInstrumentation.waitForIdleSync();
    -
    -      this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
    -
    - -

    Turning off touch mode

    -

    - To control the emulator or a device with key events you send from your tests, you must turn off - touch mode. If you do not do this, the key events are ignored. -

    -

    - To turn off touch mode, you invoke - ActivityInstrumentationTestCase2.setActivityTouchMode(false) - before you call getActivity() to start the activity. You must invoke the - method in a test method that is not running on the UI thread. For this reason, you - can't invoke the touch mode method from a test method that is annotated with - @UIThread. Instead, invoke the touch mode method from setUp(). -

    -

    Unlocking the emulator or device

    -

    - You may find that UI tests don't work if the emulator's or device's home screen is disabled with - the keyguard pattern. This is because the application under test can't receive key events sent ' - by sendKeys(). The best way to avoid this is to start your emulator or device - first and then disable the keyguard for the home screen. -

    -

    - You can also explicitly disable the keyguard. To do this, - you need to add a permission in the manifest file (AndroidManifest.xml) and - then disable the keyguard in your application under test. Note, though, that you either have to - remove this before you publish your application, or you have to disable it programmatically in - the published app. -

    -

    - To add the the permission, add the element - <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/> - as a child of the <manifest> element. To disable the KeyGuard, add the - following code to the onCreate() method of activities you intend to test: -

    -
    -  mKeyGuardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    -  mLock = mKeyGuardManager.newKeyguardLock("activity_classname");
    -  mLock.disableKeyguard();
    -
    -

    where activity_classname is the class name of the activity.

    -

    Troubleshooting UI tests

    -

    - This section lists some of the common test failures you may encounter in UI testing, and their - causes: -

    -
    -
    WrongThreadException
    -
    -

    Problem:

    - For a failed test, the Failure Trace contains the following error message: - - android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created - a view hierarchy can touch its views. - -

    Probable Cause:

    - This error is common if you tried to send UI events to the UI thread from outside the UI - thread. This commonly happens if you send UI events from the test application, but you don't - use the @UIThread annotation or the runOnUiThread() method. The - test method tried to interact with the UI outside the UI thread. -

    Suggested Resolution:

    - Run the interaction on the UI thread. Use a test class that provides instrumentation. See - the previous section Testing on the UI Thread - for more details. -
    -
    java.lang.RuntimeException
    -
    -

    Problem:

    - For a failed test, the Failure Trace contains the following error message: - - java.lang.RuntimeException: This method can not be called from the main application thread - -

    Probable Cause:

    - This error is common if your test method is annotated with @UiThreadTest but - then tries to do something outside the UI thread or tries to invoke - runOnUiThread(). -

    Suggested Resolution:

    - Remove the @UiThreadTest annotation, remove the runOnUiThread() - call, or re-factor your tests. -
    -
    - diff --git a/docs/html/guide/topics/testing/what_to_test.jd b/docs/html/guide/topics/testing/what_to_test.jd new file mode 100644 index 0000000000000..e13538ad139d8 --- /dev/null +++ b/docs/html/guide/topics/testing/what_to_test.jd @@ -0,0 +1,84 @@ +page.title=What To Test +@jd:body +

    + As you develop Android applications, knowing what to test is as important as knowing how to + test. This document lists some most common Android-related situations that you should consider + when you test, even at the unit test level. This is not an exhaustive list, and you consult the + documentation for the features that you use for more ideas. The + android-developers Google Groups + site is another resource for information about testing. +

    +

    Ideas for Testing

    +

    + The following sections are organized by behaviors or situations that you should test. Each + section contains a scenario that further illustrates the situation and the test or tests you + should do. +

    +

    Change in orientation

    +

    + For devices that support multiple orientations, Android detects a change in orientation when + the user turns the device so that the display is "landscape" (long edge is horizontal) instead + of "portrait" (long edge is vertical). +

    +

    + When Android detects a change in orientation, its default behavior is to destroy and then + re-start the foreground Activity. You should consider testing the following: +

    + +

    Change in configuration

    +

    + A situation that is more general than a change in orientation is a change in the device's + configuration, such as a change in the availability of a keyboard or a change in system + language. +

    +

    + A change in configuration also triggers the default behavior of destroying and then restarting + the foreground Activity. Besides testing that the application maintains the UI and its + transaction state, you should also test that the application updates itself to respond + correctly to the new configuration. +

    +

    Battery life

    +

    + Mobile devices primarily run on battery power. A device has finite "battery budget", and when it + is gone, the device is useless until it is recharged. You need to write your application to + minimize battery usage, you need to test its battery performance, and you need to test the + methods that manage battery usage. +

    +

    + Techniques for minimizing battery usage were presented at the 2010 Google I/O conference in the + presentation + + Coding for Life -- Battery Life, That Is. This presentation describes the impact on battery + life of various operations, and the ways you can design your application to minimize these + impacts. When you code your application to reduce battery usage, you also write the + appropriate unit tests. +

    +

    Dependence on external resources

    +

    + If your application depends on network access, SMS, Bluetooth, or GPS, then you should + test what happens when the resource or resources are not available. +

    +

    + For example, if your application uses the network,it can notify the user if access is + unavailable, or disable network-related features, or do both. For GPS, it can switch to + IP-based location awareness. It can also wait for WiFi access before doing large data transfers, + since WiFi transfers maximize battery usage compared to transfers over 3G or EDGE. +

    +

    + You can use the emulator to test network access and bandwidth. To learn more, please see + Network Speed Emulation. + To test GPS, you can use the emulator console and {@link android.location.LocationManager}. To + learn more about the emulator console, please see + + Using the Emulator Console. +

    diff --git a/docs/html/images/testing/android_test_framework.png b/docs/html/images/testing/android_test_framework.png index 6f80530021d74..459975c06c124 100755 Binary files a/docs/html/images/testing/android_test_framework.png and b/docs/html/images/testing/android_test_framework.png differ diff --git a/docs/html/images/testing/test_framework.png b/docs/html/images/testing/test_framework.png new file mode 100644 index 0000000000000..fbc5fc2ad42b0 Binary files /dev/null and b/docs/html/images/testing/test_framework.png differ