Android Test Basics

Source: Internet
Author: User

The Android test Framework (Android testing framework) is part of the development environment and provides the architecture and powerful tools to help you test all aspects of your application from the unit to the framework.


Key Features:

    • Based on JUnit, you can test some classes that are not related to Android APS directly using JUnit, or use Android's Juint extension to test Android components. If you're just starting out with Android testing, you can start by writing some common-purpose test cases from androidtestcase before you write more complex test cases.
    • The android Juint extension provides test classes for specific Android components, and provides methods for creating mock object helper methods and controlling component lifecycles.
    • Test suite is included in the testing package, and the action is similar to the main package.
    • Eclipse ADT contains the SDK tools for creating and testing, and can be used in other Ides from the command line. These tools read information from the app being tested and automatically create test package build files, mainfest files and file directory structures.
    • The SDK provides Moneyrunner (written in Python script) and Monkey (UI stress test tool that sends pseudo-random events).


This document describes the basics of the Android test framework, including the test architecture, the API for developing tests, and the tools to start testing and view test results. This article assumes that you have the basics of Android app programming and JUnit testing.

The test framework diagram is as follows:

Test structure

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

The Android test is based on JUnit. Typically, JUnit testing is the method of testing the application under test. The test method consists of a class that is test cases (or test suites).

JUnit compiles the test source files into the class file. Similarly, in Android, the test source file in the test package is compiled with the Android compilation tool as a class file. Test runner in JUnit to execute the testing class. Use the test tool in Android to load the test package and the application being tested, and then call the Android Test Runner.

Test Project

A test project is a catalog or Eclipse project where you can create new source code, manifest files, and other files for the test package. We recommend using the Android tool to create a test project:

    • Automatically configures the Instrumentationtestrunner as the test executor. You must use Instrumentationtestrunner or its subclasses to perform junit tests.
    • Take the appropriate name for the test package. If the test is applied to the Com.mydomain.myapp,android tool, the automatic name testing package is named Com.mydomain.myapp.test.
    • Automatically create appropriate build files, manifest files, and directory structures.


Recommended directory structure:

  myproject/      androidmanifest.xml      res/for           main application)      src/          for main application) ... tests/ androidmanifest.xml res/for tests) src/fortests)
              

Note: This is often different in practice depending on the IDE, whichever instance of the IDE is specified.


Test API

The Android Test API is based on the JUnit API and extends the instrumentation framework and Android-specific test classes.

Junit


Using the JUnit TestCase class, you can unit test classes that do not use the Android API. TestCase is also the base class for Androidtestcase (testing for Android-dependent objects). Androidtestcase also offers Android-specific setup, teardown, and other help methods.

The Assert class of JUnit can display the result, the Assert method compares the expected value with the actual result, and throws an exception when the comparison fails. Android also provides an assertion class that extends the comparison type, as well as the assertion class used to test the UI.

Note The Android Test API supports the code style of JUnit 3 and does not support JUnit 4.

Instrumentation

Android Instrumentation is a series of control methods or hooks (hooks) in the Android system. These hooks can control the components independently within the normal life cycle. It can also control how Android loads apps.

Usually the Android component will run according to the life cycle specified by the system, for example, the activity's life cycle starts when it is intent activated, its OnCreate () method is called, followed by Onresume (), and when the user launches another application, OnPause () method is called, and if the activity calls the finish () method, its OnDestroy () method is also called. The Android Framework API does not provide a way for you to invoke these callback methods directly in your code, but you can use instrumentation.

The system runs all the components in the application in the same process, and you can have some components, such as content provider, running in a separate process. However, you cannot force an app to run in the same process as another running app.

With Android Imstrumentation, you can call the callback method directly in the test code, allowing you to penetrate the component's life cycle, just like debugging. The following test code demonstrates how to use instrumentation to test the activity save and restore 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 Starti Ng position Assertequals (test_state_destroy_position, currentposition);        


The key method used in the code is getactivity (), which belongs to the Android instrumentation API. This method is called to start the activity. You can configure the environment (test fixture) required for testing in advance.

Instrumentation can load a test package and be tested to the same process, so that the test code can invoke the method of applying the component, modifying and checking the fields in the pieces.

Test Case Class


Android provides several test case classes that inherit from TestCase and assert, all of which have Andorid-specific setup, teardown, and other helper methods.


Androidtestcase


The generic test case class inherits the TestCase and assert classes. It provides the setup () and teardown () methods in standard JUnit, along with the JUnit assert method. It also provides methods to test permissions and to prevent memory leaks by clearing certain class references.

Component-specific test case

An important feature of the Android test framework is the component test case class. They have a unique setup and teardown and control component life cycle. They also provide mock methods.

1. Activity Testing

2. Content Provider Testing

3. Service Testing

Android does not provide a separate test case class for Broadcastreceiver. You can test the broadcastreceiver by sending a intent object to its component by testing it to check if the broadcastreceiver reply is correct.

Applicationtestcase


Test the setup and teardown of the Application object with Applicationtestcase. These objects maintain the global state of all component information in the application package, which verifies that the <application> elements in the manifest file are properly configured. However, remember that this test case does not control the testing of the application package component.

Instrumentationtestcase

If you want to use the instrumentation method in the test case class, you must use Instrumentationtestcase or its subclasses. The Activity test case inherits the base class.

Assertion class

The Android test case class inherits from JUnit, and you can use assertions to display test results. The assertion method compares the actual value returned by the test with the expected values and throws assertionexception if the comparison fails. Using assertion is more convenient than printing log and has better test performance.

In addition to the methods of the JUnit assert class, the test API also provides the Moreasserts and Viewasserts classes:

    • Moreasserts contains more powerful assertions, such as a Assertcontainsregex (string, string) that matches a regular expression.
    • Viewasserts contains many assertions about the view, for example, it contains a asserthasscreencoordinates (view, view, int, int) method to test whether the view is in a specific (x, Y) position on the screen, These assertions simplify the geometry and alignment tests in the UI.
Simulating object classes


To resolve dependencies in the testing process, Android provides classes that create mock system objects, such as context objects, ContentProvider objects, Contentresolver objects, and service objects. Some test cases can simulate the intent object. By using these mock objects, you can isolate the test from the rest of the system and also satisfy the dependencies in the test, which are in the package android.test and Android.test.mock.

Simulation objects isolate the test from the running system by piling or overloading the normal operation. For example, the Mockcontentresolver object replaces the usual resolver framework with its own native framework that is isolated from the system. At the same time Mockcontentresolver does not use the Notifychange (Uri, Contentobserver, Boolean) method so that observer objects other than the test environment are not accidentally triggered.

The Mock object class also satisfies the test dependency by providing subclasses of the normal class, which in addition to the method you overwrite is not working. For example, the Mockresources object is a subclass of the resources class, and each method throws an exception when it is called. To use it, you just need to reload the required method.

The following are the emulated object classes available in Android:

Basic Mock object classes

Mockapplication, Mockcontext, Mockcontentprovider, Mockcursor, Mockdialoginterface, Mockpackagemanager and Mockresources provide a simple and useful simulation strategy (piling) that throws a Unsupportedoperationexception exception when called. Using it, you just need to reload the required method.

Note: Mockcontentprovider and Mockcursor are newly added in API Level 8.

Resolver Mock objects

Mockcontentresolver provides isolated testing for content provider by shielding the normal resolver framework of the system. Instead of looking for a content provider that provides authority in the system, Mockcontentresolver uses its own internal table, you must explicitly use AddProvider (String, ContentProvider) method to add provider to the table.

With this feature you can associate the simulated content provider with authority, create a new provider object but use the test data, and you can even set the authority of the provider to NULL. The Mockcontentresolver object actually isolates your test from the provider that contains the real data. You can control the functionality of provider and prevent testing from affecting real data.


Context Test


Android provides two context classes to provide testing:

    • The Isolatedcontext class provides an isolated context in which files, directories, and database operations using the context are in the test area. Although limited in functionality, it is sufficient to respond to system calls, allowing the application's data operations to be tested without affecting real data on the current device.
    • Most of the functionality of the Renamingdelegatingcontext context is handled by the existing context, but the file and database operations are handled by Isolatedcontext, and the isolated part uses a test directory, and create special files and directory names, you can control the naming yourself, you can also let constructor automatically specify. This class provides a quick way to create an isolated area for data manipulation without affecting other normal operations in the context.
Run Tests

The test case is run by the Test Runner class, and the test runner loads the testing case class, initialization, run, and cleanup tests. The Android test runner must be configured so that the system tools that launch the application can control how the test package is loaded with the test case and the application being tested. Typically set in the manifest file.

Instrumentationtestrunner is the main test runner class in Android, which extends the JUnit Test Runner framework and is configured to perform any test case provided by the Android system Class and supports all types of tests.

You can specify that the <instrumentation> tag content of the manifest file for the test package is instrumentation or its subclasses. The Instrumentationtestrunner code is in the shared library Android.test.runner, so it is usually not linked to your code and must be specified in the <uses-library> tab. The Eclipse ADT and Android command-line tools automatically generate them and add them to the manifest file of the test package, usually without having to manually set them up.

Note: If you are using Test runner other than Instrumentationtestrunner, you must modify the <instrumentation> tag and point to the class you want to use.

To run the Instrumentationtestrunner class, you must invoke the internal system class with the Android tool. These classes are automatically called in Eclipse ADT and run by the command-line tool when the test is executed with Android Debug Bridge (ADB).

The system class loads and starts the test package, kills the processes that are being tested for the application package, and reloads the entities of the test package, and then gives control to Instrumentationtestrunner, which executes each test case in the testing package. You can also control which test case or method runs through the setting in Eclipse ADT or flag in the command-line tool.

Neither the system class nor the Instrumentationtestrunner run the tested application, but the test case. It either invokes the method in the package being tested, or calls its own method to change the test package life cycle. The application is fully controlled by the test case, which is initialized by the test case before testing begins.

For more run tests, you can see testing from Eclipse with ADT and testing from other IDEs.

View Test Results

The Android test framework returns the test results to the tool that launched the test. The results are displayed in the new JUnit View panel in Eclipse ADT, and the command line is displayed in stdout. Both can see a summary of each test case name and the method you are running, and you will see all the failed assertions that contain a link to the row where the test code that failed was generated. The failed assertion also lists the expected and actual values.

The test results vary from one IDE to another.


Monkey and Monkeyrunner


The SDK provides two application testing tools:

    • Ui/application exerciser Monkey, commonly referred to as "Monkey", is a command-line tool that sends pseudo-random event streams (such as keystrokes, touches, gestures) to the device. You can run it through Android Debug Bridge (ADB), stress test your application, and report the errors you encounter. You can repeat the steps by using the same random number seed each time.
    • Monkeyrunner is a set of APIs, based on Python. The API includes the ability to connect to devices, install and uninstall packages, compare pictures, and run test apps that correspond to your app. With this API, you can write powerful, complex tests that run through the command-line tool Monkeyrunner.

Process Package Name

The

test environment requires both the Android app package name and the Java package identifier to be processed. They all use the same naming format, but they represent a completely different entity. The

Android package name is a unique system name corresponding to the. apk file, set by the "Android:package" attribute in the <manifest> tag in the manifest file of the app package. The name of the test package must be different from the name of the package being tested, usually the Android tool will use the name of the test package with ". Test" as the name of the test package. The

Test package also uses the package name to locate the application it is testing, the meta


The Java package identifier corresponds to the source file, and the package name reflects the directory where the source file resides, and it affects the accessibility of the class to the members.

The Android tool will help you set the name of the test package. Depending on your input, the tool will set the name of the test package and the name of the target package for the test. These tools will only work if the application project being tested already exists.

By default, these tools set the package identifier of the test class to match the package designator of the application being tested. If you want to expose some of the members of the package that you are testing, you may need to make some changes. If you want to modify, just modify the Java package identifier, do not modify the Android package name, just modify the source file of test case and not modify the package name of the R.java file in the package, because modifying it will cause conflicts with the R.java class in the package being tested. Do not modify the Android package name of the test package to be the same as the package name of the app it is testing, because their names are no longer unique in the system.

Test content

The to test describes in detail the key features that should be tested in Android apps and the conditions that might affect that functionality.

Most of the unit tests are specific to the Andorid component that you are testing. There is a section in Activity testing, Content Provider testing, and Service testing that lists "what to test."

Try to run these tests on a real device. Second, use Android emulator to load the hardware, screen, and version of the Android vitual device that you have configured to test.

Resources

Http://developer.android.com/intl/zh-cn/tools/testing/testing_android.html

Http://www.uml.org.cn/mobiledev/201306074.asp

This address: http://www.cnblogs.com/pythontesting/p/4916574.html

Android Test Basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.