Android Programming Unit Test Example detailed (source code) _android

Source: Internet
Author: User
Tags gettext stub touch

This example describes the Android programming unit test. Share to everyone for your reference, specific as follows:

Full instance code code click here to download the site.

This article is based on the previous article, "Unit Test for Java programming (JUNIT) example analysis" to continue to explain the Android unit test, the Android source code introduced the Java Unit Test framework (Android source code directory: libcore\junit\src\ Main\java\junit\framework), and then extend the test framework that belongs to Android on the basis of the Java Unit Test framework. The diagram of the Android concrete framework class is as follows:

As you can see from the class diagram above, the Android test class enables you to test (Activity,service,contentprovider, even application) the most important components of Android.

In fact, in the Android source code, basically each system application with a test project, the following map of the source code settings (set) module:

The tests folder in the diagram above is the unit test project that the settings module comes with, and interested readers can read the source code themselves.

Eclipse (of course, the premise is to ensure that the relevant Android environment in Eclipse has been built) for Android unit testing:

1.Application of testing:

To create a new Android project, add an inherited application class to the Android project with the following code:

Package com.phicomm.hu; 
Import android.app.Application; 
public class Fxandroidapplication extends application 
{ 
 @Override public 
 void OnCreate () 
 { 
  // TODO auto-generated Method Stub 
  super.oncreate (); 
 } 
 @Override public 
 void Onterminate () 
 { 
  //TODO auto-generated method Stub 
  super.onterminate (); 
 } Public 
 String Getfavourite () 
 {return 
  ' I love Java '; 
 } 
} 

After the Appication class is created, then create a corresponding test project: Select its Android project----> right mouse button----->new---->android Test Project-----> Enter the test project name--->next-----> select the target Android project (here is Fxandroidapplication's Android project). In this way, a test project is created and completed.

Creating automatically generated test projects and Android projects through eclipse there is no big difference in structure, mainly in Androidmanifest.xml, as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemas.android.com/apk/res/" Android " 
 package=" com.phicomm.hu.test " 
 android:versioncode=" 1 " 
 android:versionname=" 1.0 "> 
 <uses-sdk android:minsdkversion= "/> 
 <instrumentation 
  android:name=" Android.test.InstrumentationTestRunner " 
  android:targetpackage=" com.phicomm.hu "/> 
 <application 
  android:icon= "@drawable/ic_launcher" 
  android:label= "@string/app_name" > 
  <uses-library Android:name= "Android.test.runner"/> 
 </application> 
</manifest> 

The relevant test environment (which is unique to Android) was registered in Androidmanifest.xml: <uses-library android:name= "Android.test.runner"/> Implementation uses the associated run test class library, <instrumentation/> in Targetpackage as the package where the tested class resides.

Next, create the Fxandroidapplicationd test class in the test project, the following code:

Package com.phicomm.hu.test; 
Import com.phicomm.hu.FxAndroidApplication; 
Import android.app.Application; 
Import Android.test.ApplicationTestCase; 
public class Fxapplicationtest extends applicationtestcase<fxandroidapplication>
{ 
 private Fxandroidapplication apptest; 
 Public Fxapplicationtest () 
 { 
  //invokes the parent class constructor, and the parameter passed in the constructor is the class 
  super (Fxandroidapplication.class) being tested; 
 @Override 
 protected void SetUp () throws Exception 
 { 
  //TODO auto-generated method stub 
  Super.setup (); 
  The method that must be invoked before obtaining the application 
  createapplication (); 
  Gets the fxandroidapplication 
  apptest = getapplication () to be tested 
 ; 
 Test Fxandroidapplication Getfavourite method public 
 void Testgetfavourite () 
 {/ 
  * Verify that the predictive value "I love C + +" equals the actual value , 
  because the actual value is "I love Java", the test results here are failure*/ 
  assertequals ("I love C + +", apptest.getfavourite ()); 
 } 


Once the test class is created, you can test the Fxandroidapplicationd.

Test method:

Start the Android Simulator (also through the Android phone)-----> Run the android project-----> Check the Test class fxapplicationtest----> The right mouse button--->run As---->android Junit Test. In this way, the test results can be displayed in the Eclipse's JUnit view, as shown in the following figure:

The test results from the above figure show that there are two test methods in the Applicationtestcase test class that are tested by default (Testgetfavourite is the method we want to test).

Of course, you can also test through the ADB: Connect the android phone------> Open the Computer Command window (start--> Run---> enter cmd)----> enter the ADB shell----in the command window >am Instrument-w Com.phicomm.hu.test (the package name where the test case is located)/android.test.instrumentationtestrunner.

2.Activity of testing:

Like the application above, create an Android project that creates two activity, an activity that implements the login interface for entering user information, and another acticity displays the user information entered.

The effect chart is as follows:

The code for the login interface fxloginactivity is as follows:

Package com.phicomm.hu; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
Import Android.widget.EditText; 
 public class Fxloginactivity extends activity {private EditText userName; 
 Private EditText PassWord; /** called the activity is a. 
  * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.main); 
  UserName = (edittext) Findviewbyid (r.id.name); 
  PassWord = (edittext) Findviewbyid (R.ID.PSD); 
  Button login = (button) Findviewbyid (R.id.login); 
   button reset = (Button) Findviewbyid (R.id.reset); Listen for login button Login.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {//     
    TODO auto-generated Method Stub Intent Intent = new Intent (fxloginactivity.this, Fxresultactivity.class); Through inTent passes the login information to the Resultactivity interface to display Intent.putextra ("UserName", Username.gettext (). toString ()); 
    Intent.putextra ("PassWord", Password.gettext (). toString ()); 
   Start resultactivity Display Login interface information startactivity (intent); 
   } 
  }); 
    Listen for reset button Reset.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) { 
   TODO auto-generated Method Stub resetinput (); 
 } 
  }); 
  public void Resetinput () {Username.settext (""); 
 Password.settext ("");

 } 
}

The code for the

Main.xml layout file is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <edittext android:id= "@+id/name" android:layout_width= fill_parent "android:layout_height=" wrap_content "Android:hint=" @string/name "/> <edittext android:id=" @+id/psd "android:layout_width=" Fill_parent "an droid:layout_height= "Wrap_content" android:hint= "@string/psd"/> <linearlayout android:orientation= "horizon Tal "Android:layout_width=" match_parent "android:layout_height=" Wrap_content "> <button Android : id= "@+id/login" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:layout_wei ght= "1" android:text= "@string/login"/> <button android:id= "@+id/reset" android:layout_width= "fill _parent "android:layout_height="Wrap_content "android:layout_weight=" 1 "android:text=" @string/reset "/> </LinearLayout> </linearl

 Ayout>

The Fxresultactivity code to display the user information interface is as follows:

Package com.phicomm.hu; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.widget.EditText; 
Import Android.widget.TextView; 
public class Fxresultactivity extends activity 
{ 
 private static final String TAG = "resultactivity"; 
 @Override 
 protected void onCreate (Bundle savedinstancestate) 
 { 
  //TODO auto-generated method stub 
  super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.result); 
  TextView result = (TextView) Findviewbyid (r.id.result); 
  By getting Intent get the information from the login interface 
  Intent Intent = Getintent (); 
  String userName = Intent.getstringextra ("UserName"); 
  String PassWord = Intent.getstringextra ("PassWord"); 
  Displays the login information in the page 
  Result.settext ("Username: + userName +" \ n "+" password: + PassWord);  
 } 
 

After the Android project is created, create a corresponding test project:

The test code for the corresponding Fxloginactivity class in the

Test project is as follows (detailed code explains the comments in the code, which is not burdensome):

Package com.phicomm.hu.test; 
Import android.app.Instrumentation; 
Import Android.test.ActivityInstrumentationTestCase2; 
Import android.view.KeyEvent; 
Import Android.widget.Button; 
Import Android.widget.EditText; 
Import com.phicomm.hu.FxLoginActivity; public class Fxloginactivitytest extends activityinstrumentationtestcase2<fxloginactivity> {private 
 Instrumentation minstrumentation; 
 Private Fxloginactivity mlogintest; 
 Private EditText UserName; 
 Private EditText PassWord; 
 Private Button login; 
 private Button Reset; 
 Public Fxloginactivitytest () {super (Fxloginactivity.class);  //Rewrite the SetUp method to perform the associated initialization @Override protected void SetUp () throws Exception {//TODO auto-generated method 
  Stub super.setup (); 
  /** This program needs to enter user information and password, that is, the need to send key events, * So, you must call Getactivity before calling the following method to close the * touch mode, otherwise key events will be ignored//close touch mode 
  Setactivityinitialtouchmode (FALSE); 
  Minstrumentation = Getinstrumentation (); 
  Get the fxloginactivity being testedMlogintest = Getactivity (); 
  Gets the fxloginactivity-related UI Component UserName = (edittext) Mlogintest.findviewbyid (com.phicomm.hu.r.id.name); 
  PassWord = (edittext) Mlogintest.findviewbyid (COM.PHICOMM.HU.R.ID.PSD); 
  Login = (Button) Mlogintest.findviewbyid (Com.phicomm.hu.r.id.login);  
 reset = (Button) Mlogintest.findviewbyid (Com.phicomm.hu.r.id.reset); 
  //The test case implementation before testing other use cases, the test ensures that the obtained component is not empty public void testpreconditions () {assertnotnull (mlogintest); 
  Assertnotnull (UserName); 
  Assertnotnull (PassWord); 
  Assertnotnull (login); 
 Assertnotnull (reset); /** This method enables you to enter related login information on the login interface. 
  Because the * related processing of the UI component (such as the request focus here) needs to be implemented on the UI thread, the Runonuithread method implementation of the activity must be invoked. 
    */public void input () {Mlogintest.runonuithread (new Runnable () {@Override public void run () { 
    TODO auto-generated Method Stub username.requestfocus (); 
   Username.performclick (); 
  } 
  }); 
   /* Because test cases are executed on a separate thread, you need to synchronize application here, * call Waitforidlesync wait for the test thread to synchronize with the UI thread for input. * WAitforidlesync and SendKeys are not allowed to run in the UI thread/Minstrumentation.waitforidlesync (); 
    Call the SendKeys method and enter the username SendKeys (keyevent.keycode_p, Keyevent.keycode_h, Keyevent.keycode_i, Keyevent.keycode_c, 
  Keyevent.keycode_o, Keyevent.keycode_m, keyevent.keycode_m); Mlogintest.runonuithread (New Runnable () {@Override public void run () {//TODO auto-generated method 
    Stub Password.requestfocus (); 
   Password.performclick (); 
  } 
  }); 
 Call the SendKeys method, enter the password SendKeys (keyevent.keycode_1, keyevent.keycode_2, Keyevent.keycode_3, keyevent.keycode_4); 
  ///Test input user Information public void Testinput () {//Call Test class input method, implement input user information (SendKeys input) input (); 
  The test verifies that the expected value of the user information is equal to the actual value assertequals ("Phicomm", Username.gettext (). toString ()); 
  The expected value of the password 123 and the actual value of 1234 does not match, failure; 
 Assertequals ("123", Password.gettext (). toString ()); 
  //Test Login button public void Testlogin () {input (); Opens a new thread and executes the operation on the UI thread through this thread Minstrumentation.runonmainsync (new RunNable () {@Override public void run () {//TODO auto-generated Method Stub login.requestfocus (); 
   Login.performclick (); 
 } 
  }); 
  //test reset button public void Testreset () {input (); Minstrumentation.runonmainsync (New Runnable () {@Override public void run () {//TODO auto-generated m 
    Ethod stub reset.requestfocus (); 
   Click on the button Reset.performclick (); 
  } 
  }); 
  Verify that the Reset button is implemented and that the content is blank assertequals ("", Username.gettext (). toString ()); 
 Assertequals ("", Password.gettext (). toString ()); 

 } 
}

Run the test class for testing (select---->run as--->android Junit test), and then automatically start the emulator for the relevant input-click Test. Note: The test can be found when the program is tested to the Testlogin () method login to another interface, the test stopped, that is, Testreset () did not test. Therefore, you need to test the testreset () can be testlogin () comment out, otherwise the program will test to Testlogin () after the Testreset () is not tested.

Fxresultactivity's test class code is as follows:

Package com.phicomm.hu.test; 
Import android.content.Intent; 
Import Android.test.ActivityInstrumentationTestCase2; 
Import Android.widget.TextView; 
Import com.phicomm.hu.FxResultActivity; public class Fxresultactivitytest extends activityinstrumentationtestcase2<fxresultactivity> {private static fi 
 nal String login_info = "Username: feixun\n Password: 123"; 
 Private Fxresultactivity mresultactivity; 
 Private TextView result; 
 Public Fxresultactivitytest () {super (Fxresultactivity.class); 
  @Override protected void SetUp () throws Exception {//TODO auto-generated Method Stub super.setup (); 
  Create Intent, passing the user's login information via Intent Intent Intent = new Intent (); 
  Intent.putextra ("UserName", "Feixun"); 
  Intent.putextra ("PassWord", "123"); Start fxresultactivity mresultactivity = Launchactivitywithintent ("com.phicomm.hu") by carrying the intent of the user login information, Fxresultactivit 
  Y.class, intent); 
Gets the UI component result = (TextView) Mresultactivity.findviewbyid (Com.phicomm.hu.r.id.result); //test verifies that the user's logon information is public void Testlogininfo () {//verifies that the expected value equals the actual value assertequals (Login_info, Result.gettext (). Tostri 
 Ng ());

 } 
}

Run the test class above and the results are correct.

I hope this article will help you with the Android program.

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.