第一步:新建一个TestCase,记得要继承androidTestCase,才能有getContext()来获取当前的上下文变量,这在Android测试中很重要的,因为很多的Android api都需要context。
Java代码
- publicclassTestMathextendsAndroidTestCase{
- privateinti1;
- privateinti2;
- staticfinalStringLOG_TAG="MathTest";
- @Override
- protectedvoidsetUp()throwsException{
- i1=2;
- i2=3;
- }
- publicvoidtestAdd(){
- assertTrue("testAddfailed",((i1+i2)==5));
- }
- publicvoidtestDec(){
- assertTrue("testDecfailed",((i2-i1)==1));
- }
- @Override
- protectedvoidtearDown()throwsException{
- super.tearDown();
- }
- @Override
- publicvoidtestAndroidTestCaseSetupProperly(){
- super.testAndroidTestCaseSetupProperly();
- //Log.d(LOG_TAG,"testAndroidTestCaseSetupProperly");
- }
- }
第二步:新建一个TestSuit,这个就继承Junit的TestSuite就可以了,注意这里是用的addTestSuite方法,一开始使用addTest方法就是不能成功。
Java代码
- publicclassExampleSuiteextendsTestSuite{
- publicExampleSuite(){
- addTestSuite(TestMath.class);
- }
- }
第三步:新建一个Activity,用来启动单元测试,并显示测试结果。系统的AndroidTestRunner竟然什么连个UI界面也没有实现,这里只是最简单的实现了一个
Java代码
- publicclassTestActivityextendsActivity{
- privateTextViewresultView;
- privateTextViewbarView;
- privateTextViewmessageView;
- privateThreadtestRunnerThread;
- privatestaticfinalintSHOW_RESULT=0;
- privatestaticfinalintERROR_FIND=1;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- resultView=(TextView)findViewById(R.id.ResultView);
- barView=(TextView)findViewById(R.id.BarView);
- messageView=(TextView)findViewById(R.id.MessageView);
- Buttonlunch=(Button)findViewById(R.id.LunchButton);
- lunch.setOnClickListener(newView.OnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- startTest();
- }
- });
- }
- privatevoidshowMessage(Stringmessage){
- hander.sendMessage(hander.obtainMessage(ERROR_FIND,message));
- }
- privatevoidshowResult(Stringtext){
- hander.sendMessage(hander.obtainMessage(SHOW_RESULT,text));
- }
- privatesynchronizedvoidstartTest(){
- if(testRunnerThread!=null
- &&testRunnerThread.isAlive()){
- testRunnerThread=null;
- }
- if(testRunnerThread==null){
- testRunnerThread=newThread(newTestRunner(this));
- testRunnerThread.start();
- }else{
- Toast.makeText(this,
- "Testisstillrunning",
- Toast.LENGTH_SHORT).show();
- }
- }
- publicHandlerhander=newHandler(){
- publicvoidhandleMessage(Messagemsg){
- switch(msg.what){
- caseSHOW_RESULT:
- resultView.setText(msg.obj.toString());
- break;
- caseERROR_FIND:
- messageView.append(msg.obj.toString());
- barView.setBackgroundColor(Color.RED);
- break;
- default:
- break;
- }
- }
- };
- classTestRunnerimplementsRunnable,TestListener{
- privateActivityparentActivity;
- privateinttestCount;
- privateinterrorCount;
- privateintfailureCount;
- publicTestRunner(ActivityparentActivity){
- this.parentActivity=parentActivity;
- }
- @Override
- publicvoidrun(){
- testCount=0;
- errorCount=0;
- failureCount=0;
- ExampleSuitesuite=newExampleSuite();
- AndroidTestRunnertestRunner=newAndroidTestRunner();
- testRunner.setTest(suite);
- testRunner.addTestListener(this);
- testRunner.setContext(parentActivity);
- testRunner.runTest();
- }
- @Override
- publicvoidaddError(Testtest,Throwablet){
- errorCount++;
- showMessage(t.getMessage()+"\n");
- }
- @Override
- publicvoidaddFailure(Testtest,AssertionFailedErrort){
- failureCount++;
- showMessage(t.getMessage()+"\n");
- }
- @Override
- publicvoidendTest(Testtest){
- showResult(getResult());
- }
- @Override
- publicvoidstartTest(Testtest){
- testCount++;
- }
- privateStringgetResult(){
- intsuccessCount=testCount-failureCount-errorCount;
- return"Test:"+testCount+"Success:"+successCount+"Failed:"+failureCount+"Error:"+errorCount;
- }
- }
- }
第四步:修改AndroidManifest.xml,加入,不然会提示找不到AndroidTestRunner,这里需要注意是这句话是放在applications下面的,我一开始也不知道,放错了地方,浪费了不少时间
Xml代码
- xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:Android="http://schemas.Android.com/apk/res/Android"
- package="com.test.sample"
- Android:versionCode="1"
- Android:versionName="1.0">
- <applicationAndroid:icon="@drawable/icon"Android:label="@string/app_name"Android:debuggable="true">
- <activityAndroid:name=".TestActivity"
- Android:label="@string/app_name">
- <intent-filter>
- <actionAndroid:name="Android.intent.action.MAIN"/>
- <categoryAndroid:name="Android.intent.category.LAUNCHER"/>
- intent-filter>
- activity>
- <uses-libraryAndroid:name="Android.test.runner"/>
- application>
- <uses-sdkAndroid:minSdkVersion="4"/>
- manifest>