Android testing basics and android Testing
The android Testing Framework is part of the development environment. It provides the architecture and powerful tools to help you test applications from the unit to the Framework.
Key features:
- Based on JUnit, you can directly use JUnit to test classes irrelevant to Android AP, or use Android JUint extension to test Android components. If you are new to Android testing, you can first write some general purpose test cases from AndroidTestCase, and then write more complex test cases.
- Android JUint extension provides a test class for Android-specific components, an auxiliary method for creating mock objects, and a method for controlling the life cycle of components.
- Test suite is included in the Test package. The operation is similar to that of the main package.
- Eclipse ADT contains the SDK tools for creation and testing and can be used in other ides through the command line. These tools read information from the tested application and automatically create the build File, mainfest file, and file directory structure of the test package.
- The SDK provides moneyrunner (scripts written in python) and Monkey (UI stress testing tool for sending pseudo-random events ).
This document describes the basis of the android testing framework, including the test structure, APIs for development and testing, and tools for starting and viewing test results. This article assumes that you have the foundation for android Application Programming and JUnit testing.
The test framework diagram is as follows:
Test Structure
The android build and test tool assumes that the test project is organized into a standard structure similar to the test, test class, test package, and test project.
Android testing is based on JUnit. JUnit testing is usually used to test the "application to be tested" method. The class of the test method is test cases (or test suites ).
Compile the test source file in JUnit to the class file. Similarly, the test source file in the test package is compiled using the android compilation tool in android. Test runner in JUnit to execute the test class. Use a test tool in android to load test packages and applications to be tested, and then call test runner of android.
Test Item
A test project is a directory or eclipse project where you can create source code, manifest files, and other files of the test package. We recommend that you use Android tool to create a test project:
- The InstrumentationTestRunner is automatically configured as the test executor. You must use InstrumentationTestRunner or its subclass to perform the JUnit test.
- Name the test package. If the app to be tested is com. mydomain. myapp, Android tool automatically names the test package com. mydomain. myapp. test.
- Automatically create appropriate build files, manifest files, and directory structures.
Recommended 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)
Note: The actual operation is usually different from the IDE. Please refer to the actual IDE instance.
Test API
The Android testing API is based on the JUnit API and extends the instrumentation framework and the test classes specific to Android.
JUnit
You can use the TestCase class of JUnit to perform unit tests on classes that do not use android APIs. TestCase is also the base class of AndroidTestCase (android-dependent objects for testing. AndroidTestCase also provides 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 a comparison-type asserted class and an asserted class used to test the UI.
Note that the android test API supports the code style of JUnit 3 and does not support JUnit 4.
Instrumentation
Android instrumentation is a series of hooks in the android system ). These hooks can independently control components within the normal life cycle. It also controls how android loads applications.
Generally, android components run according to the lifecycle specified by the system. For example, when an Activity is activated by Intent, its onCreate () method is called, followed by onResume (), when you start another application, the onPause () method is called. If the Activity calls the finish () method, its onDestroy () method is also called. The android framework API does not provide methods for you to directly call these callback methods in code, but you can use instrumentation.
The system runs all the components in the application in the same process. You can run some components, such as content provider, in a separate process. However, you cannot force the application to run in the same process as other running applications.
With the android imstrumentation, you can directly call the callback method in the test code, allowing you to penetrate the life cycle of the component, just like debugging. The following test code demonstrates how to use instrumentation to test the Activity's save and restore status:
// 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 in the Code is getActivity (), which belongs to the android instrumentation API. This method is called to start the Activity. You can configure the test fixture environment in advance ).
Instrumentation can load the test package and the tested application to the same process, so that the test code can call the method of the Application Component, modify and check the fields in the component.
Test case class
Android provides several test case classes inherited from TestCase and Assert. They all have andorid-specific setup, teardown, and other auxiliary methods.
AndroidTestCase
The general test case class inherits the TestCase and Assert classes. It provides the setup () and teardown () methods in the standard JUnit, as well as the Assert methods of JUnit. In addition, it provides methods to test permissions and methods to prevent memory leakage by clearing certain class references.
Test case exclusive to components
An important feature of the android testing framework is the test case class component. They have unique setup and teardown and control component lifecycles. They also provide the mock method.
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 testing the component that sends the Intent object to it and check whether the BroadcastReceiver reply is correct.
ApplicationTestCase
Use ApplicationTestCase to test setup and teardown of the Application object. These objects maintain the global status of all component information in the application package. The test case is used to verify that the <application> element in the manifest file is correctly configured. However, remember that this test case cannot control the testing of application package components.
InstrumentationTestCase
To use the instrumentation method in the test case class, you must use InstrumentationTestCase or its subclass. Activity test case inherits the base class.
Assertion class
The Android test case class inherits from JUnit and can be used to display the test results. The assertion method compares the actual value returned by the test with the expected value. If the comparison fails, AssertionException is thrown. Using Assertion is more convenient than printing logs and has better test performance.
In addition to the JUnit Assert class method, the test API also provides the MoreAsserts and ViewAsserts classes:
- MoreAsserts contains more powerful assertions, such as assertContainsRegex (String, String) matching regular expressions ).
- ViewAsserts contains many assertions about the View. For example, it contains the assertHasScreenCoordinates (View, View, int, int) method used to test whether the View is at a specific (x, y) Position on the screen, these assertions simplify geometric and aligning tests in the UI.
Simulated Object Class
To solve the dependencies during the test, Android provides classes for creating simulated system objects, such as Context objects, ContentProvider objects, ContentResolver objects, and Service objects. Some Intent objects that can be simulated by test case. By using these simulated objects, you can isolate the test from the rest of the system and satisfy the dependencies in the test. These classes are packaged in android. test and android. test. mock.
The simulated object isolates the test from the running system by piling or reloading normal operations. For example, the MockContentResolver object uses its own local framework isolated from the system to replace the General resolver framework. At the same time, MockContentResolver does not use the policychange (Uri, ContentObserver, boolean) method, so that the observer objects outside the test environment will not be accidentally triggered.
The simulated object class also satisfies the test dependency by providing subclass of the normal class. This subclass does not work except the method you override. For example, the MockResources object is a subclass of the Resources class, and an exception is thrown during the call of each method. To use it, you only need to reload the required method.
The following lists the simulated object classes available in Android:
Basic Simulated Object Class
MockApplication, MockContext, MockContentProvider, MockCursor, MockDialogInterface, MockPackageManager, and MockResources provide simple and useful simulation policies (Piling). During the call, an UnsupportedOperationException is thrown. To use it, you only need to reload the required methods.
Note: MockContentProvider and MockCursor are newly added to API Level 8.
Resolver Simulated Object
MockContentResolver provides an isolated test for the content provider by shielding the system's normal resolver framework. MockContentResolver does not search for the content provider that provides authority in the system, but uses its own internal table. You must explicitly add the provider to the table using addProvider (String, ContentProvider.
Through this feature, you can associate the simulated content provider with authority. You can create a new provider object but use test data. You can even set the authority of the provider to null. In fact, the MockContentResolver object isolates your test from the provider that contains real data. You can control the provider function and prevent testing from affecting real data.
Context Test
Android provides two Context classes for testing:
- The IsolatedContext class provides an isolated Context. All files, directories, and database operations using this Context are in the test area. Despite its limited functionality, it is sufficient to respond to system calls and allow data operations on the application to be tested without affecting the real data on the current device.
- Most of the Context functions of RenamingDelegatingContext are processed by the existing Context, but all file and database operations are handled by IsolatedContext. The isolated part uses a test directory, create a special file and directory name. You can control the name by yourself, or enable the constructor to automatically specify the name. This class provides a quick way to create an isolated region for data operations without affecting other normal operations of Context.
Run the test
Test case is run by the test runner class, and test runner loads the test case class, initializes, runs, and cleans up the test. Android test runner must be configured, so that the system tool that starts the application can control how the test package loads the test case and the tested application. It is generally set in the manifest file.
InstrumentationTestRunner is the main test runner class in android. It extends the JUnit test runner framework and is configured to execute the test case class provided by any android system and supports all types of tests.
You can specify the <instrumentation> label content of the manifest file of the test package as Instrumentation or its subclass. The Code of InstrumentationTestRunner is in the android. test. runner shared library. Therefore, it is usually not linked to your code and must be specified in the <uses-library> label. Generally, you do not need to manually set them. Eclipse ADT and android command line tools will automatically generate them and add them to the manifest file of the test package.
Note: If you are using a test runner other than InstrumentationTestRunner, you must modify the <instrumentation> label and point it to the class you want to use.
To run the InstrumentationTestRunner class, you must use the android tool to call the internal system class. These classes are automatically called in Eclipse ADT. When the command line tool runs the test, it uses Android Debug Bridge (adb) to run these classes.
The system class loads and starts the test package, kills the running process of the tested application package, reloads the entity of the tested package, and then gives the control to the InstrumentationTestRunner, it is used to execute each test case in the test package. You can also use setting in Eclipse ADT or flag in the command line tool to control which test cases or methods are run.
It is neither a system class nor an InstrumentationTestRunner running the tested application, but a test case. It either calls the method in the tested package or calls its own method to change the lifecycle of the tested package. Applications are completely controlled by test case. test case is used to initialize the test environment before the test starts,
For more running tests, see Testing from Eclipse with ADT and Testing from Other IDEs.
View test results
The Android testing framework returns the test result to the tool that starts the test. The results in eclipse ADT are displayed in the new JUnit view panel, and the command line is displayed in STDOUT. Both display the name of each test case and the summary of the method you are running, and all the failed assertions, including links to the row where the failed test code is generated. Failure assertions also list the expected values and actual values.
The test results vary with the IDE.
Monkey and monkeyrunner
The SDK provides two application testing tools:
- The UI/Application Exerciser Monkey, usually called "monkey", is a command line tool that sends a pseudo-random event stream (such as a key, touch, or gesture) to a device. You can run Android Debug Bridge (adb) to test the application stress and report errors. You can repeat the steps by using the same Random Seed each time.
- Monkeyrunner is an API Based on Python. This API provides the following functions: connect to a device, install and uninstall software packages, compare images, and run the test application corresponding to the application. Through this API, you can write out powerful and complex tests and run them using the command line tool monkeyrunner.
Processing Package name
In the test environment, the android application package name and java package identifier must be processed simultaneously. They all use the same naming format, but they represent completely different entities.
The androidpackage name is a unique system name corresponding to the .apk file. It is set by the "android: package" attribute in the <manifest> label of the manifest file of the application package. The name of the test package must be different from that of the tested package. Generally, the android tool adds ". test" to the name of the tested package.
The test package also uses the package name to locate the application it is testing. The Meta is set by the <instrumentation> "android: targetPackage" attribute in the manifest file of the test package.
The java package identifier corresponds to the source file. The package name reflects the directory where the source file is located. It also affects the accessibility between classes and members.
The android tool will help you set the name of the test package. Based on your input, the tool sets the name of the test package and the name of the test target package. These tools work only when the tested application project already exists.
By default, these tools set the package identifier of the test class to be consistent with the package identifier of the tested application. If you want to expose some Members in the tested package, you may need to make some modifications. If you want to modify, only modify the java package identifier, do not modify the android package name, only modify the source file of test case, and do not modify the R. the package name of the java file, because modifying it will cause the R. java class conflict. Do not change the android package name of the test package to the same name as the package name of the application it tests, because their names are no longer unique in the system.
Test content
What To Test describes in detail the key functions that should be tested in android applications and the status that may affect this function.
Most unit tests are specific to the andorid component you are testing. The Activity Testing, Content Provider Testing, and Service Testing sections list what to test ".
Try to run these tests on real devices. Next, use Android Emulator to load the android vitual device that has been configured with the hardware, screen, and version you want to test.
References
Http://developer.android.com/intl/zh-cn/tools/testing/testing_android.html
Http://www.uml.org.cn/mobiledev/201306074.asp
Address: http://www.cnblogs.com/pythontesting/p/4916574.html