Android 006 unit test

Source: Internet
Author: User

Android 006 unit test
Android testing and log testing common test categories
Before introducing Android Junit, let's first introduce the common test categories.

 


Depends on whether the source code is known:


 Black box testing: I do not know the source code, but only test the functions of the program.
White box testing: know the source code and test it based on the source code.

 


Depends on the test granularity: (module size)


Unit test
Testing function: function test: Method test
Integration test: Testing of several modules and joint debugging of servers/clients
Testing system: system test

 


Testing: (brute-force testing)

 

Smoke test: the smoke test keeps running until the system crashes.

Google provides a monkey
Adb shell: Enter the simulator directory, monkey
2000. monkey is used for 2000 random clicks.
Monkey-p package name count: test only one application


Pressure test: pressure test

 


Junit testing framework


 Run the test code: the background will help us perform two steps


Upload the current application to the mobile phone system
The supervisor sends an instruction to notify the mobile phone to test the uploaded code.


Configure the following in the configuration file:
Add Instruction Set (under the manifest node)
Android: name = "android. test. InstrumentationTestRunner"
Android: targetPackage = "com. example. sqlitephone"/>

TargetPackage: The target package for testing.


The explain Instruction Set depends on the jar package (under the application node)

 



Junit Test Procedure

 

 

 

Unit Test

In actual development, the process of developing android software must be continuously tested. The Junit testing framework is a required technology for formal Android development. Android encapsulates the Junit testing framework and can simulate the correctness of sending events and detecting program processing.

* Android unit test implementation process

1. Add a Test Library

Add a Test Library to the node of AndroidManifest. xml.

2. Set the test environment

 

3. Compile the test class

-Get context getContext ()-inherit from AndroidTestCase

-AssertEquals ()

-View test results

We have completed a business method and want to test it. The Android program cannot write the main
To run the method, you need to create a test project.


1. Create a test project
Creating a test project
Define project name
Select the project to test

When creating a test class, you must inherit AndroidTestCase.
Compile a test class
You can directly use the business class in the project to be tested. The test method must start with "test" in lower case.

2. Do not create a test project and add a test class.
Add the configuration in the AndroidManifest. xml configuration file.
<Instrumentation android: targetPackage = "cn. itcast. junit"
Android: name = "android. test. InstrumentationTestRunner"/>

Define a class that inherits AndroidTestCase and defines the test method.


Junit unit test


 New Business Method
For example, the addition of a calculator:
// Calculator
Public class Calc {
/**
* Calculator Addition Method
* @ Param x
* @ Param y
* @ Return
*/
Public int add (int x, int y ){
Return x + y;
}
}
 Create a Junit test class and perform unit tests on the add method.

// AndroidTestCase must be inherited for unit tests in Android.
Public class TestCalc extends AndroidTestCase {
// Write a test method.
Public void testAdd (){
// You want to test the method for adding a calculator.
Calc calc = new Calc ();
Int result = calc. add (5, 6 );
// Assertions
AssertEquals (11, result );
}
}
Add test commands to the inventory file

Android: name = "android. test. InstrumentationTestRunner"
Android: targetPackage = "com. itheima. unit"
Android: label = "Tests for My App"/>
Testing Method testAdd
Double-click the method and right-click Run As -- Android Junit Test
Running result: Green bars indicate that the test is successful.


Junit unit testing will be used in the company, so you need to master it.

Android Junit development knowledge
Note: to expand your knowledge, you do not have to master it. You can use it to further improve your understanding.
For more information, see.
Android
The core of the test environment is an Instrumentation framework. Under this framework, your test application
You can precisely control applications. Use Instrumentation,
You can create simulated system objects, such as Context, before the main program starts.
Multiple lifecycles; send UI events to applications; check program status during execution.
The Instrumentation framework implements these functions by running the main program and the test program in the same process.
.
Add
Add To specify the application to be tested. The features of this element indicate the need to test
The name of the application package and how to run the test program on Android. The following picture Summary
Describes the Android testing environment:
In
In Android, the test program is also an Android program. Therefore, it is written in the same way as the tested program.
Many of them are the same. The SDK helps you create the main program project and its test project at the same time. You
You can use the ADT plug-in of Eclipse or the command line to run the Android test. Eclipse ADT provides
A large number of tools are used to create test cases, run and view results.
Android provides a testing API Based on the JUnit testing framework to write test cases and programs.
In addition, Android provides a powerful Instrumentation framework that allows test cases to access programs.
Status and runtime object.


Main core APIs in Android Junit
 JUnit TestCase class
The TestCase inherited from JUnit cannot use the Instrumentation framework. But these classes contain
The method used to access system objects (such as Context. Use
Context, you can browse resources, files, databases, and so on. The base class is AndroidTestCase,
Generally, its subclass is associated with a specific component.
Subclass:
 ApplicationTestCase --
Test the entire application class. It allows you to inject a simulated Context to the application
Initialize the test parameters before the application starts, and
Check the application before destruction.
 ProviderTestCase2 --
Test the class of a single ContentProvider. Because it requires MockContentResolve
R, and inject an IsolatedContext. Therefore, the Provider test is isolated from the OS.
.
 ServiceTestCase --
Test the class of a single Service. You can inject a simulated Context or a simulated Appl.
Or let Android provide you with Context and MockApplic.
.
 Instrumentation TestCase class
Inherited from JUnit
The TestCase class and can be used to test the Activity by using the Instrumentation framework. Use Instrument
Ation, Android can
To send events to the program for automatic UI testing, and can precisely control the startup of the Activity, monitoring Ac
The status of tietong lifecycle.
The base class is InstrumentationTestCase. All its sub-classes can send buttons or touch events.
To the UI. Subclass can also inject a simulated Intent. Subclass:
Extends ActivityTestCase -- base class of the Activity test class.
 SingleLaunchActivityTestCase --
Test the class of a single Activity. It can trigger setup () and tearDown () once, instead
Each method is triggered when it is called. If your testing method is for the same Activity
Then use it.
Issued by Employment Service Department of Blackhorse Android Course Notes
SyncBaseInstrumentation -- Test Content
Provider synchronous class. It uses Instrumentation before testing synchronization starts.
Cancel an existing synchronization object.
 ActivityUnitTestCase --
A single test class for a single Activity. Using it, You can inject the simulated Cont
Ext or Application, or both. It is used to perform unit tests on the Activity. Different
In other Instrumentation classes, this test class cannot inject a simulated Intent.
 ActivityInstrumentationTestCase2 --
Test the class of a single Activity in a normal system environment. You cannot inject a simulated
Context, but you can inject a simulated Intent. In addition, you can also
Program (main thread of the Application) to run the test method, and you can send
Send buttons and touch events.
 Assert class
Android also inherits the Assert class of JUnit, which has two sub-classes: MoreAsserts and Vi.
EwAsserts.
The  MoreAsserts class contains more powerful asserted methods, such as assertContainsRegex (Stri
Ng, String), which can be used for regular expression matching.
The specified ViewAsserts class contains information about Android
AssertHasScreenCoordinates (View, View,
Int,
Int) to test the specific X and Y positions of the View in the visible area. Simplified Assert
Test the UI ry and alignment in the UI.
 Mock object class
Android
Some classes can easily create simulated system objects, such as Application, Context, Content
Resolver and Resource. Android also provides some methods In some test classes to create simulated In
Tent. Because these simulated objects are easier to make than the actual objects
Therefore, using them can simplify dependency injection. You can go to android. test and android. test. mock
.
They are:
 IsolatedContext --
Simulate a Context so that the application can run in isolation. At the same time, there are large
The amount of Code helps us complete communication with Context. This class is useful in unit testing.
.
Issued by Employment Service Department of Blackhorse Android Course Notes
 RenamingDelegatingContext --
When you modify the default file and database name, you can delegate most functions to a storage
On the general Context. Use this class to test files and databases and
System Context.
 MockApplication, MockContentResolver, MockContext, MockDialogInter
Face, MockPackageManager, MockResources --
Creates a Simulated System Object Class. They only expose those useful for object management.
Method. The default implementation of these methods only throws an exception. You need to inherit these classes and override them.
These methods.
 Instrumentation TestRunner
Android
Provides a custom class for running test cases, called InstrumentationTestRunner. This class of control
The application is in the test environment and runs the test in the same process.
Program and main program, and output the test results to the appropriate place. IntrumentationTestRunner
The key to control the entire test environment during runtime is the use
Instrumentation. Note that if your test class does not use Instrumentation, you can also
Use this TestRunner.
When you run a test program, a system tool called Activity is first run.
Manager. Activity
Manager uses the Instrumentation framework to start and control TestRunner.
To use
Intrumentation to close the instance of any main program, and then start the test program and the main program (the same
In process ). This ensures direct interaction between the test program and the main program.
Work in testing environment
Tests on Android programs are included in a test program, which is also an Android
Application. The test program exists as a separate Android project, which is similar to a normal Android program.
The same files and folders. The test project specifies the application to be tested in the manifest file.
Each test program contains one or more test cases for specific types of components. In the test case
Defines testing methods for certain parts of the application. When you run the test program, Android will
Load the main program in the same process, and then trigger the test method in each test case.
Test Project
To start testing an Android program, you need to use the Android tool to create a test.
Project. The tool creates project folders, files, and required subfolders. The tool also creates
The nifest file that specifies the application to be tested.
Issued by Employment Service Department of Blackhorse Android Course Notes
Test Cases
A test program contains one or more test cases inherited from Android
TestCase class. Selecting a test case class depends on the type of the Android component you want to test and your
What kind of test is required. A test program can test different components, but each test case class is set
Timing can only test a single type of components.
Some Android components have multiple associated test case classes. In this case
Between classes, you need to determine the test type you want to perform. For example, for an Activity, you have two options:
ActivityInstrumentationTestCase2 and ActivityUnitTestCase.
ActivityInstrumentationTestCase2 is designed for some functional tests. Therefore
Test the Activity in a normal system environment. You can inject a simulated Intent, but not
Is a simulated Context. Generally, you cannot simulate the dependency between activities. In comparison,
CtivityUnitTestCase is designed for unit testing, so it is tested in an isolated system environment
Activity. In other words, when you use this test class, the Activity cannot interact with other activities.
.
As an empirical rule, if you want to test the interaction between Activity and Android, use Acti
VityInstrumentationTestCase2. If you want to perform a regression test on an Activity, use
TivityUnitTestCase.
Test Method
Each test case class provides a way to establish a test environment and control applications. For example,
All test case classes provide the setUp () method of JUnit to build the test environment. In addition, you can
Add methods to define separate tests. When you run the test program, each added method will run
Once. If you override the setUp () method, it runs before each method is run. Similar
The tearDown () method runs after each method.
The test case class provides a large number of methods for starting and stopping components. For this reason,
In the Running Test
Before, you need to explicitly tell Android to start a component. For example, you can use getActivity () to start
Create an Activity. During the entire test case, you can only call
Use this method once, or each test method once. You can call
Use its finishing () to destroy the Activity, and then call getActivity () to restart the Activity.
Run the test and view the result
After compiling the test project, you can use the system tool Activity
Manager to run the test program. You give Activity
The Manager provides the TestRunner name (usually InstrumentationTestRunner, in the program
The name includes the package name and TestRunner name of the program to be tested. Activity
The Manager loads and starts your test program, kills any instance of the main program, and then
Load the main program in the same process, and then pass the first test case of the test program. This time
Wait, TestRunner takes over these test cases and runs each test method until all
Method running is complete.
Issued by Employment Service Department of Blackhorse Android Course Notes
If you use Eclipse, the result is displayed on the JUnit panel. If you use the command line,
Output to STDOUT.
Test what?
In addition to some functional tests, here are some content you should consider for testing:
Activity lifecycle events: You should test the correctness of Activity processing lifecycle events. For example,
An Activity should be in a pause or destroy event.
Save its status. Remember that changes in the screen direction will also cause the current Activity to be destroyed, because
Therefore, you need to test this accidental situation to ensure that the application status is not lost.
Database Operations: You should ensure that database operations can correctly handle changes in application status. Use and
The simulated object in roid. test. mock.
Screen Size and resolution: Before releasing a program, make sure that the screen size and resolution to be run are all
. You can use AVD for testing, or use a real target device for testing.
Testing in the UI thread
The Activity runs in the UI thread of the program. After the UI is initialized
After the te () method, all interactions with the UI must run in the UI thread. When you run the program normally, it
You have the permission to access this thread, and nothing special happens. When you run the test program
This has changed. In the class with instrumentation, You can trigger the method on the UI line
. This is not allowed for other test case classes.
To run a complete test method in the UI thread, you can use @ UIThreadTest
Declare the thread. Note that all statements in the method will be run in the UI thread. Do not interwork with the UI
Mutual methods cannot do this. For example, you cannot trigger Instrumentation. waitForIdleSync ().
If you want some code in the method to run in the UI thread, create an anonymous Runnabl
E object, put the code in the run () method, and then pass this object to appActivity. runOnUiThr
Ead (). Here, appActivity is the app object you want to test.

 


Log Information
LogCat Introduction
Android
There are two ways to obtain LogCat: 1. The LogCat view provided by DDMS 2. The adb command line
The LogCat view provided by mongoddms is as follows:

If the view is not opened, click window> show view> other> android-
> Logcat.
You can select or add filtering information on the left side of the view. When you run an application
To filter this package. Select the log Level of LogCat in the upper-right corner of the view.
Bose, debug, info, warn, error, and assert6 are optional. :
.
The main part of this view is log details, including the error Level, time (Tim
E), process ID (PID), thread ID (TID), Application package name (Application), tag (
Tag), log body (Text ).
The TID is not equivalent to Thread. currentThread (). getId () in Java, but Linux
Thread ID, which is the same as PID.
Using the command line to call LogCat
 Display LogCat information on the console
Enter adb logcat in the console
Press the Enter key to view the LogCat information. If you need to terminate the operation, press Ctrl + C.
 Saves LogCat information in the file

Run adb logcat> D:/a.txt
The log is output to the D:/a.txt file. Press Ctrl + C to terminate the log output.
The above is about adb.
The simplest use of the logcat command, in fact, this command also has a variety of optional parameters to choose from, it is not detailed here
Detailed description.


Logcat Log Level
Android. util. Log has the following five common methods:
Log. v () Log. d () Log. I () Log. w () and Log. e (). Corresponds to VERBOSE according to the first letter
, DEBUG, INFO, WARN, ERROR.
Audit Log. v
The debugging color is black, and any message will be output. Here, v stands for verbose.
Log. v ("","");
The output color of mongolog. d is blue. Only debug debugging is output, but It outputs the upper-layer messages.
And you can use the Logcat label of DDMS to filter the data.
The output of Alibaba Log. I is green. Generally, it indicates message information. It does not output Log. v and Log.
. D information, but will display I, w and e information, System. out output information is Info level
Commit Log. w indicates orange, which can be seen as a warning of warning. We generally need to pay attention to the optimization And
Roid code. If you select the roid code, the Log. e information is output.
When audit Log. e is red, you can think of error errors. Only red error messages are displayed.
We need to analyze the stack information carefully.
In the logging program, we can use the Log class to output information.

Result:
Logcat uses tag Filtering
Tag: You can use tags to filter logs.
You can add a LOG filter in logcat and select the log level to display the current level and ratio.
High level. Select warn. logs of warn and error are displayed. You can also use System.
Out to print logs (info level), System. error (warning level)
Logcat log Activation
Activate log. Click one of devices in ddms. In fact, logs are printed in the simulator.
The system passes the log information to the logcat of the Development Platform through adb.
If the log is still not printed, restart adb or eclipse, and then run the command adb.
Logcat. You can view logs in cmd.

Case study: Obtain LogCat information from the Android Program
The following shows how to obtain LogCat information in real time by creating an Android project.

 

 


Create a new project named LogCat
Use the default MainActivity. java class and default layout file in this project.
Modify layout File
Xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical"
Tools: context = ". MainActivity">
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "Get LogCat"
Android: id = "@ + id/bt_click"
/>
Android: id = "@ + id/TV _show"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: hint = "display log"
/>


Modify MainActivity. java code
The first part of the code:
Package com.itheima.com. logcat;
Import java. io. BufferedReader;
Import java. io. InputStreamReader;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. util. Log;
Import android. view. View;
Import android. widget. Button;
Import android. widget. TextView;
Public class MainActivity extends Activity {
Protected static final String TAG = "MyTest ";
Private Button btn;
Private TextView TV _show;
Private Handler handler = new Handler (){
Public void handleMessage (android. OS. Message msg ){
TV _show.setText (String) msg. obj );
};
};
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Btn = (Button) findViewById (R. id. bt_click );
TV _show = (TextView) findViewById (R. id. TV _show );
Issued by Employment Service Department of Blackhorse Android Course Notes
The second part of the Code:
Btn. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
Log. v (TAG, "this is verbose information ");
Log. d (TAG, "this is debug information ");
Log. I (TAG, "this is info information ");
Log. w (TAG, "this is warn information ");
Log. e (TAG, "this is error information ");
/** Enable the thread to listen to log output information **/
New Thread (new Runnable (){
@ Override
Public void run (){
Process mLogcatProc = null;
BufferedReader reader = null;
Try {
/*
*
Run the command line to obtain the LogCat information.
*/
MLogcatProc =
Runtime.getruntime(cmd.exe c (new String [] {"logcat", TAG + ": v *: s"
});
/*
* Get the process output stream object
*/
Reader = new
BufferedReader (new
InputStreamReader (mLogcatProc. getInputStream ()));
String line = null;
StringBuilder sb = new
StringBuilder ();

Part 3 (end) of the Code ):
While (line = reader. readLine ())! = Null ){
Sb. append (line );
Message msg =
Message. obtain ();
Msg. obj =
Sb. toString ();
Handler. sendMessage (msg );
}
Reader. close ();
/*
*
Notify the main thread to modify the TextView object by sending a message
*
Therefore, this operation is performed in the Child thread, while the Android Application neutron thread cannot modify the UI (UI Modification
The operation must be in
* In the main thread
*
Therefore, Android provides a Handler mechanism to allow the sub-thread to send messages to the main thread, and then the main thread modifies the U

I).*/} catch (Exception e) {e.printStackTrace();}}}).start();}});}}


Supervisor runs the project on the simulator and click the button
Running result:
Work and interview
Token is being interviewed
 Junit Test
The interview may be asked, how did your company test it before?
You can say that our company is more standardized, and some functions will be tested using Junit. You can also say that,
We perform a manual test. If the test is complete, submit it to the tester for testing.
Then they submit the bug and fix it.
Shard log information
During the interview, I will be asked, How did you solve the bug?
Generally, breakpoint debugging, variable analysis, and log tracking are all you need.
Variable analysis is used to monitor the value of a variable during breakpoint debugging to check whether it is null.
Or abnormal.
Worker working
 Junit Test

This can be used. Generally, small companies will not perform the Junit test, that is, hand testing. Large
Companies with strict regulations may require Junit testing. A normal ticket is required.
Meta-test, so we need to master the unit test.
It is mainly for testers to write test cases for testing.
Shard log information
As mentioned above, this is more important. You must view the log information and
Analysis, bug debugging is very helpful.
In addition, some students' logs sometimes fail to appear. Refer to the Logcat log for activation,
Generally, the device is not connected successfully. After the connection, you may need to select the connected device.

 

 

 

 

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.