How to perform Android unit testing
- Menifest.xml Add:
<application> Join in:
<uses-library android:name= "Android.test.runner"/>
<application> outside join:
<uses-permission android:name= "Android.permission.RUN_INSTRUMENTATION"/>
<instrumentation android:name= "Android.test.InstrumentationTestRunner" android:targetpackage= " Name.feisky.android.test "
Android:label= "Test for my App"/>
- Writing unit test code: must inherit from Androidtestcase class
Package name.feisky.android.test;
Import Android.test.AndroidTestCase;
Import Junit.framework.Assert;
public class MyTest extends Androidtestcase {
private static final String tag= "MyTest";
public void Testsave () throws Throwable
{
int i=4+8;
Assert.assertequals (5,i);
}
public void Testsomethingelse () throws Throwable {
Assert.asserttrue (1 + 1 = = 12);
}
}
- Perform tests
IntelliJ Medium:
In eclipse: Right-click Run as Android JUnit Test
Command-line tools:
ADB shell am instrument-w name.feisky.android.test/android.test.instrumentationtestrunner
You can also create a new test project to test
- New > Project > android > android Test Project.
- To add a test case class
Add new class, base class set to Android.test.activityinstrumentationtestcase2
- adding constructors
Add the Setup () method, which initializes the variables and test environment before all the tests.
@Override
protected void SetUp () throws Exception {
Super.setup ();
Mactivity = This.getactivity ();
MView = (TextView) Mactivity.findviewbyid (Com.example.helloandroid.r.id.textview);
resourcestring = mactivity.getstring (Com.example.helloandroid.r.string.hello);
}
- Add the Testpreconditions () method, check the initialization environment, execute only once
public void Testpreconditions () {
Assertnotnull (MView);
}
- Adding unit Tests
public void Testtext () {
Assertequals (resourcestring, (String) Mview.gettext ());
Android Unit Test