Android unit test-JUnit and androidjunit

Source: Internet
Author: User

Android unit test-JUnit and androidjunit

With the development of testing in recent years, we often see recruitment information for testing engineers. There is a unit test such a JUnit in Java

Currently, Android is mainly written in Java, so in Android development, there will also be a unit test --- JUnit. Build an Android Development Environment

As you can see, Android must first import the Android SDK Development Environment Based on JDK. Of course, the Android unit test JUnit is dedicated to testing Android.

The method performance in the APP. The most common test for Android is JUnit. Android provides a series of powerful test tools, which are used to expand the Android environment.

Industry Standard JUnit testing framework. Although you can use JUnit to test the Android project, the Android tool allows you to perform more complex tasks for all aspects of the application.

Testing, including unit and framework.


I. Main features of the Android testing environment include:
1. You can access Android objects.
2. The Instrumentation framework can control and test applications.
3. Simulate versions of common Android objects.
4. A tool that runs a single test or test suite with or without Instrumentation.
5. You can use the Eclipse ADT plug-in and command line to manage the Test and Test projects.


Ii. JUnit core framework ----- Instrumentation framework:

The core of the Android testing environment is an Instrumentation framework. Under this framework, your testing application can precisely control the application. With Instrumentation, you can create simulated system objects, such as Context, control multiple lifecycles of applications, and send UI events to applications before the main program starts; check the program status during execution. The Instrumentation framework implements these functions by running the main program and the test program in the same process.
Add the <instrumentation> element to the manifest file of the test project to specify the application to be tested. The feature of this element specifies the name of the application package to be tested and shows Android how to run the test program. In Android, the test program is also an Android program. Therefore, it has many similarities with the writing method of the tested program. The SDK helps you create the main program project and its test project at the same time. You can run the Android test through the Eclipse ADT plug-in or command line. Eclipse's ADT provides a large number of tools to create test cases, run and view results.

First, let's take a look at the android testing class hierarchy:

Testing API
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 Program states and runtime objects.

JUnit TestCase class
The TestCase inherited from JUnit cannot use the Instrumentation framework. However, these classes contain methods for accessing system objects (such as Context. With Context, you can browse resources, files, databases, and so on. The base class is AndroidTestCase, which is generally a subclass of it and is associated with a specific component.

Subclass:

1. ApplicationTestCase -- test the entire application class. It allows you to inject a simulated Context into the application, initialize the test parameters before the application starts, and check the application before it is destroyed after the application ends.
2. ProviderTestCase2 -- test the class of a single ContentProvider. Because MockContentResolver is required and an IsolatedContext is injected, Provider testing is isolated from OS.
3. ServiceTestCase -- test the class of a single Service. You can inject a simulated Context or simulated Application (or both), or let Android provide Context and MockApplication for you.

Instrumentation TestCase class
It inherits from the JUnit TestCase class and can use the Instrumentation framework to test the Activity. With Instrumentation, Android can send events to the program for automatic UI testing, precisely control the startup of the Activity, and monitor the status of the Activity 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:
1. ActivityTestCase -- base class of the Activity test class.
2. SingleLaunchActivityTestCase -- test the class of a single Activity. It can trigger setup () and tearDown () once, instead of triggering each method call. If your testing method is for the same Activity, use it.
3. SyncBaseInstrumentation-test the synchronization class of the Content Provider. It uses Instrumentation to cancel existing synchronization objects before starting the test synchronization.
4. ActivityUnitTestCase: a single test class for a single Activity. Using it, You can inject the simulated Context or Application, or both. It is used to perform unit tests on the Activity.
Unlike other Instrumentation classes, this test class cannot be injected with a simulated Intent.
5. 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 run the test method in the UI thread (the main thread of the Application), and send buttons and touch events to the application UI.


Iii. Test usage of the Instrumentation framework

The Instrumentation and Activity are a bit similar, but the Activity requires an interface, and the Instrumentation is not like this. We can understand it as a kind of graphic interface without startup capability, tool class used to monitor other classes (declared using Target Package.

The following is a simple example to explain the basic testing method of Instrumentation.

1. First, create an Android project named Sample. The Code is as follows:
Public class Sample extends Activity {
Private TextView myText = null;
Private Button button = null;
 
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MyText = (TextView) findViewById (R. id. text1 );
Button = (Button) findViewById (R. id. button1 );
Button. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View arg0 ){
MyText. setText ("Hello Android ");
}
});
}
 
Public int add (int I, int j ){
Return (I + j );
}
}
The function of this program is relatively simple. After clicking the button, the content of TextView changes from Hello to Hello Android. at the same time, in this class, I also wrote a simple add method, which is not called and is only for testing.

2. Add a test package to the src folder and add a test class SampleTest to the test package.
The code for the test class is as follows:
Public class SampleTest extends InstrumentationTestCase {
Private Sample sample = null;
Private Button button = null;
Private TextView text = null;
 
/*
* Initial settings
* @ See junit. framework. TestCase # setUp ()
*/
@ Override
Protected void setUp (){
Try {
Super. setUp ();
} Catch (Exception e ){
E. printStackTrace ();
}
Intent intent = new Intent ();
Intent. setClassName ("com. hustophone. sample", Sample. class. getName ());
Intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
Sample = (Sample) getInstrumentation (). startActivitySync (intent );
Text = (TextView) sample. findViewById (R. id. text1 );
Button = (Button) sample. findViewById (R. id. button1 );
}
 
/*
* Garbage collection and resource recovery
* @ See android. test. InstrumentationTestCase # tearDown ()
*/
@ Override
Protected void tearDown (){
Sample. finish ();
Try {
Super. tearDown ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
 
/*
* Test the activity function.
*/
Public void testActivity () throws Exception {
Log. v ("testActivity", "test the Activity ");
SystemClock. sleep (1500 );
GetInstrumentation (). runOnMainSync (new synchronized mclick (button ));
SystemClock. sleep (3000 );
AssertEquals ("Hello Android", text. getText (). toString ());
}
 
/*
* Interface used to simulate Button clicking
*/
Private class extends mclick implements Runnable {
Button btn;
Public writable mclick (Button button ){
Btn = button;
}
 
Public void run (){
Btn. Repeated mclick ();
}
}
/*
* Methods in the test class
*/
Public void testAdd () throws Exception {
String tag = "testAdd ";
Log. v (tag, "test the method ");
Int test = sample. add (1, 1 );
AssertEquals (2, test );
}
}

The Code is as follows:
SetUp () and tearDown () are both protected methods. You can override these methods through inheritance.
Android Developer has the following explanation:
Protected void setUp ()
Since: API Level 3
Sets up the fixture, for example, open a network connection. This method is called before a test is executed.
Protected void tearDown ()
Since: API Level 3
Make sure all resources are cleaned up and garbage collected before moving on to the next test. subclasses that override this method shocould make sure they call super. tearDown () at the end of the overriding method.

SetUp () is used for initial settings, such as starting an Activity and initializing resources.
TearDown () is used for garbage collection and resource recovery.
.
In the testActivity () test method, I simulate a button click event to determine whether the program is executed as expected. Here, the invoke mclick method inherits the Runnable interface and runs simulated events through a new thread. The reason is that running directly in the UI thread may block the UI thread.

2. To perform the test correctly, you also need to modify the AndroidManifest. xml file.
<! -- Used to introduce the test database -->
<Uses-library android: name = "android. test. runner"/>
<Activity android: name = ". Sample" android: label = "@ string/app_name">
<Intent-filter>
<Action android: name = "android. intent. action. MAIN"/>
<Category android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>

<Uses-sdk android: minSdkVersion = "3"/>
<! -- Indicates the name of the target package and instrumentation to be tested. -->
<Instrumentation android: targetPackage = "com. hustophone. sample" android: name = "android. test. InstrumentationTestRunner"/>

After the above steps, you can start the test. The test methods are as follows:

(1) Use the JUnit tool integrated with Eclipse
In Eclipse, right-click the project Sample and choose Android JUnit Test from the Run as sub-menu options.


You can also use the LogCat tool to view information.


 

(2) run the unit test through the simulator

Click the Dev Tools menu on the simulator interface.

Click the Instrumentation option to go To the Instrumentation menu.



Here is an InstrumentationTestRunner, which is the test entry. Click this option to automatically run our test code. The running result is as follows:

Before clicking the button

After the button is clicked

So far, a simple test process has ended. Of course, there are still a lot of android testing content, which is also complicated. I will continue to share my experiences in the future. Now, let's get here today!


Related Article

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.