`
yidongkaifa
  • 浏览: 4052038 次
文章分类
社区版块
存档分类
最新评论

在Android上实现Junit单元测试的四部曲

 
阅读更多

第一步:新建一个TestCase,记得要继承androidTestCase,才能有getContext()来获取当前的上下文变量,这在Android测试中很重要的,因为很多的Android api都需要context。

Java代码

  1. publicclassTestMathextendsAndroidTestCase{
  2. privateinti1;
  3. privateinti2;
  4. staticfinalStringLOG_TAG="MathTest";
  5. @Override
  6. protectedvoidsetUp()throwsException{
  7. i1=2;
  8. i2=3;
  9. }
  10. publicvoidtestAdd(){
  11. assertTrue("testAddfailed",((i1+i2)==5));
  12. }
  13. publicvoidtestDec(){
  14. assertTrue("testDecfailed",((i2-i1)==1));
  15. }
  16. @Override
  17. protectedvoidtearDown()throwsException{
  18. super.tearDown();
  19. }
  20. @Override
  21. publicvoidtestAndroidTestCaseSetupProperly(){
  22. super.testAndroidTestCaseSetupProperly();
  23. //Log.d(LOG_TAG,"testAndroidTestCaseSetupProperly");
  24. }
  25. }

第二步:新建一个TestSuit,这个就继承Junit的TestSuite就可以了,注意这里是用的addTestSuite方法,一开始使用addTest方法就是不能成功。

Java代码

  1. publicclassExampleSuiteextendsTestSuite{
  2. publicExampleSuite(){
  3. addTestSuite(TestMath.class);
  4. }
  5. }

第三步:新建一个Activity,用来启动单元测试,并显示测试结果。系统的AndroidTestRunner竟然什么连个UI界面也没有实现,这里只是最简单的实现了一个

Java代码

  1. publicclassTestActivityextendsActivity{
  2. privateTextViewresultView;
  3. privateTextViewbarView;
  4. privateTextViewmessageView;
  5. privateThreadtestRunnerThread;
  6. privatestaticfinalintSHOW_RESULT=0;
  7. privatestaticfinalintERROR_FIND=1;
  8. @Override
  9. protectedvoidonCreate(BundlesavedInstanceState){
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.main);
  12. resultView=(TextView)findViewById(R.id.ResultView);
  13. barView=(TextView)findViewById(R.id.BarView);
  14. messageView=(TextView)findViewById(R.id.MessageView);
  15. Buttonlunch=(Button)findViewById(R.id.LunchButton);
  16. lunch.setOnClickListener(newView.OnClickListener(){
  17. @Override
  18. publicvoidonClick(Viewv){
  19. startTest();
  20. }
  21. });
  22. }
  23. privatevoidshowMessage(Stringmessage){
  24. hander.sendMessage(hander.obtainMessage(ERROR_FIND,message));
  25. }
  26. privatevoidshowResult(Stringtext){
  27. hander.sendMessage(hander.obtainMessage(SHOW_RESULT,text));
  28. }
  29. privatesynchronizedvoidstartTest(){
  30. if(testRunnerThread!=null
  31. &&testRunnerThread.isAlive()){
  32. testRunnerThread=null;
  33. }
  34. if(testRunnerThread==null){
  35. testRunnerThread=newThread(newTestRunner(this));
  36. testRunnerThread.start();
  37. }else{
  38. Toast.makeText(this,
  39. "Testisstillrunning",
  40. Toast.LENGTH_SHORT).show();
  41. }
  42. }
  43. publicHandlerhander=newHandler(){
  44. publicvoidhandleMessage(Messagemsg){
  45. switch(msg.what){
  46. caseSHOW_RESULT:
  47. resultView.setText(msg.obj.toString());
  48. break;
  49. caseERROR_FIND:
  50. messageView.append(msg.obj.toString());
  51. barView.setBackgroundColor(Color.RED);
  52. break;
  53. default:
  54. break;
  55. }
  56. }
  57. };
  58. classTestRunnerimplementsRunnable,TestListener{
  59. privateActivityparentActivity;
  60. privateinttestCount;
  61. privateinterrorCount;
  62. privateintfailureCount;
  63. publicTestRunner(ActivityparentActivity){
  64. this.parentActivity=parentActivity;
  65. }
  66. @Override
  67. publicvoidrun(){
  68. testCount=0;
  69. errorCount=0;
  70. failureCount=0;
  71. ExampleSuitesuite=newExampleSuite();
  72. AndroidTestRunnertestRunner=newAndroidTestRunner();
  73. testRunner.setTest(suite);
  74. testRunner.addTestListener(this);
  75. testRunner.setContext(parentActivity);
  76. testRunner.runTest();
  77. }
  78. @Override
  79. publicvoidaddError(Testtest,Throwablet){
  80. errorCount++;
  81. showMessage(t.getMessage()+"\n");
  82. }
  83. @Override
  84. publicvoidaddFailure(Testtest,AssertionFailedErrort){
  85. failureCount++;
  86. showMessage(t.getMessage()+"\n");
  87. }
  88. @Override
  89. publicvoidendTest(Testtest){
  90. showResult(getResult());
  91. }
  92. @Override
  93. publicvoidstartTest(Testtest){
  94. testCount++;
  95. }
  96. privateStringgetResult(){
  97. intsuccessCount=testCount-failureCount-errorCount;
  98. return"Test:"+testCount+"Success:"+successCount+"Failed:"+failureCount+"Error:"+errorCount;
  99. }
  100. }
  101. }

第四步:修改AndroidManifest.xml,加入,不然会提示找不到AndroidTestRunner,这里需要注意是这句话是放在applications下面的,我一开始也不知道,放错了地方,浪费了不少时间

Xml代码

  1. xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:Android="http://schemas.Android.com/apk/res/Android"
  3. package="com.test.sample"
  4. Android:versionCode="1"
  5. Android:versionName="1.0">
  6. <applicationAndroid:icon="@drawable/icon"Android:label="@string/app_name"Android:debuggable="true">
  7. <activityAndroid:name=".TestActivity"
  8. Android:label="@string/app_name">
  9. <intent-filter>
  10. <actionAndroid:name="Android.intent.action.MAIN"/>
  11. <categoryAndroid:name="Android.intent.category.LAUNCHER"/>
  12. intent-filter>
  13. activity>
  14. <uses-libraryAndroid:name="Android.test.runner"/>
  15. application>
  16. <uses-sdkAndroid:minSdkVersion="4"/>
  17. manifest>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics