How to perform android unit testing
- Add the following to menifest. xml:
<Application>Add:
<Uses-library Android: Name = "android. Test. Runner"/>
<Application>Join outside:
<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"/>
- Write unit test code: it 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 );
}
}
- Run the test
IntellijMedium:
In eclipse: Right-click Run as Android JUnit Test
Command line tool:
ADB shell am instrument-W name. feisky. Android. Test/Android. Test. instrumentationtestrunner
You can also create a test project for testing.
- New>Project>Android>Android test project.
- Add test case class
Add a new class and set the base class to Android. Test. activityinstrumentationtestcase2
- Add Constructor
Add setup () method, which initializes variables and test environments before all 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, and only execute once
Public
Void testpreconditions ()
{
Assertnotnull (mview );
}
- Add Unit Test
Public
Void testtext ()
{
Assertequals (resourcestring, (string) mview. gettext ());
}
- Test Run as...> Android JUnit Test