In the process of developing an application, it is necessary to carry out the corresponding unit test.
Next we write a simple Android application to complete the basic unit test
First, we need to build an Android project, named JUnit.
Then, create a service class, which is the class Personservice.java that needs to be tested:
Package Cn.itcast.service;public class Personservice {public void Save (string username) {String sub = username.substring ( 6);} public int Add (int a,int b) {return a+b;}}
In this class we are going to test two methods of Save (String username) and add (int a,int b).
Next, we need to configure Androidmanifest.xml this file:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Cn.itcast.files "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk ANDROID:MINSD kversion= "/> <application android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "> <!--for the introduction of test libraries, which must be placed inside the application label--<uses-library android:name= "Android.test.runner"/> & Lt;activity android:label= "@string/app_name" Android:name= ". Fileactivity "> <intent-filter > <action android:name=" Android.intent.action.MAIN "/ > <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <!--the name of the target package and instrementation that were tested, and placed outside application--><instrume Ntation android:name= "Android.test.InstrumentationTestRunner" android:targetpackage= "Cn.itcast.files" /></manifest>
It is only after configuration that we are able to use the test class correctly.
Now, we can start the test.
Build a test class Personservicetest.java, inheriting the Androidtestcase class:
Package Cn.itcast.junit;import Junit.framework.assert;import Cn.itcast.service.personservice;import Android.test.androidtestcase;public class Personservicetest extends Androidtestcase {public void Testsave () throws Exception{personservice service = new Personservice (); Service.save ("123123");} public void Testadd () throws Exception{personservice service = new Personservice (); int actual = Service.add (1, 2); Assert.assertequals (3, Actual);}}
After our test class has been set up, all we need to do is to test that these two methods do not work correctly:
Open outline View--Select the method you want to test-->run as-->android JUnit test:
We'll be able to see if the program works properly in the JUnit interface.
Android Development Series (iv): How to unit test an app