In actual development, the process of developing Android software must be continuously tested. The junint testing framework is a required technology for regular Android development. components can be obtained in junint to simulate sending events and check the correctness of program processing.Unit Testing is embedded into a project. It can also be used as a separate project to test a specific project.
Step 1: First Add the following red code to androidmanifest. xml:
<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
Package = "com. leeapps.test" Android: versioncode = "1" Android: versionname = "1.0">
<Application Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name">
<Uses-library Android: Name = "android. Test. Runner"/>
</Application>
<Use-SDK Android: minsdkversion = "6"/>
<Instrumentation Android: Name = "android. Test. instrumentationtestrunner" Android: targetpackage = "com. lee0000.test" Android: Label = "tests"/>
***The package specified by targetpackage must be the same as the application package.
Step 2: Write unit test code. Generally, name the method to be tested testxxx. Select outline (Outline View), right-click the test method, and choose "Run as"-"android JUnit test ".
For example,
Project Structure:
Androidmanifest. xml file:
<? XML version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
Package = "com. leeapps.test"
Android: versioncode = "1"
Android: versionname = "1.0" type = "codeph" text = "/codeph">
<Uses-SDK Android: minsdkversion = "15"/>
<Application
Android: icon = "@ drawable/ic_launcher"
Android: Label = "@ string/app_name">
<Activity
Android: Name = ". juinttestactivity"
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-library Android: Name = "android. Test. Runner"/>
</Application>
<Instrumentation
Android: Name = "android. Test. instrumentationtestrunner"
Android: targetpackage = "com. leeapps.test" Android: Label = "tests"/>
</Manifest>
Define two methods for testing:
Public class testclass {
Public void STR (string s ){
System. Out. println (S. substring (6 ));
}
Public int add (int A, int B ){
Return A + B;
}
}
Generally, androidtestcase is inherited. During the test, the two methods are tested. If an error occurs when "Run as"-"android JUnit test" is selected in the corresponding method, right-click the test class, select "Run as"-"Run deployments" and select:
Import JUnit. Framework. Assert;
Import Android. Test. androidtestcase;
Public class test extends androidtestcase {
Public void teststr () throws exception {
Testclass Tc = new testclass ();
TC. STR ("null ");
}
Public void testadd (){
Testclass Tc = new testclass ();
Int T = tc. Add (1, 2 );
Assert. assertequals (3, T );
}
}