I. JUnit test for Android
We have used JUnit in general, and JUnit for Android is similar. The results are green and red.
The overall unit test framework is as follows:
Here we will only introduce one of the classes: androidtestcase;
2. androidtestcase
Program Description: Create an android project: Activity, add an edittext, and do nothing else;
import android.app.Activity;import android.os.Bundle;import android.widget.EditText;public class MainActivity extends Activity {private EditText et1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et1 = (EditText)this.findViewById(R.id.et1); if(savedInstanceState!=null){ et1.setText(savedInstanceState.getString("name")); } } public int add(int a,int b){ return a+b; }}
There are usually two methods for unit testing:
(1) directly create a unit test under the project
(2) create an android test project
1. directly create a unit test class
Step 1: Add the following in androidmanifest. xml:
<Application Android: icon = "@ drawable/ic_launcher" Android: Label = "@ string/app_name"> <uses-library Android: Name = "android. test. runner "/> // Add this line of code </Application>
<Application/> <instrumentation Android: Name = "android. Test. instrumentationtestrunner" Android: targetpackage = "org. xiazdong"/> // package of the activity to be tested
Step 2: Add a unit test class
Import Org. xiazdong. mainactivity; import android. content. context; import android. test. androidtestcase; import android. widget. edittext; public class mainactivitytest extends androidtestcase {private mainactivity; private context; @ overrideprotected void setup () throws exception {super. setup (); mainactivity = new mainactivity (); // directly create the activity instance context = This. getcontext (); // obtain the context} // test the add method public void testadd () {mainactivity MA = new mainactivity (); int A = ma. add (2, 3); assertequals (5, );}}
Test;
2. Create a unit test project
The advantage is that you can directly create a test class without configuring androidmanifest. xml;
Note: This type of unit test only involves business logic, so you cannot use View-related functions such as findviewbyid. Here, we only test a business function: Add;