Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 高級開發 >> 在Android上實現Junit單元測試的四部曲

在Android上實現Junit單元測試的四部曲

編輯:高級開發

我們曾經和大家探討過全面剖析Java ME單元測試理念,其實在android實現JUnit單元測試也不是很困難,主要是在配置文件和測試環境上將花費很長時間,下面從四步簡單講一下在android上實現Junit單元測試。

第一步:新建一個TestCase,記得要繼承androidTestCase,才能有getContext()來獲取當前的上下文變量,這在Android測試中很重要的,因為很多的android api都需要context。

Java代碼

  1. public class TestMath extends androidTestCase {
  2. private int i1;
  3. private int i2;
  4. static final String LOG_TAG = "MathTest";
  5. @Override
  6. protected void setUp() throws Exception {
  7. i1 = 2;
  8. i2 = 3;
  9. }
  10. public void testAdd() {
  11. assertTrue("testAdd failed", ((i1 + i2) == 5));
  12. }
  13. public void testDec() {
  14. assertTrue("testDec failed", ((i2 - i1) == 1));
  15. }
  16. @Override
  17. protected void tearDown() throws Exception {
  18. super.tearDown();
  19. }
  20. @Override
  21. public void testandroidTestCaseSetupProperly() {
  22. super.testandroidTestCaseSetupProperly();
  23. //Log.d( LOG_TAG, "testandroidTestCaseSetupProperly" );
  24. }
  25. }

第二步:新建一個TestSuit,這個就繼承Junit的TestSuite就可以了,注意這裡是用的addTestSuite方法,一開始使用addTest方法就是不能成功。

Java代碼

  1. public class ExampleSuite extends TestSuite {
  2. public ExampleSuite() {
  3. addTestSuite(TestMath.class);
  4. }
  5. }

第三步:新建一個Activity,用來啟動單元測試,並顯示測試結果。系統的androidTestRunner竟然什麼連個UI界面也沒有實現,這裡只是最簡單的實現了一個

Java代碼

  1. public class TestActivity extends Activity {
  2. private TextView resultVIEw;
  3. private TextView barVIEw;
  4. private TextView messageVIEw;
  5. private Thread testRunnerThread;
  6. private static final int SHOW_RESULT = 0;
  7. private static final int ERROR_FIND = 1;
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  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. Button lunch = (Button)findVIEwById(R.id.LunchButton);
  16. lunch.setOnClickListener(new VIEw.OnClickListener() {
  17. @Override
  18. public void onClick(VIEw v) {
  19. startTest();
  20. }
  21. });
  22. }
  23. private void showMessage(String message) {
  24. hander.sendMessage(hander.obtainMessage(ERROR_FIND, message));
  25. }
  26. private void showResult(String text) {
  27. hander.sendMessage(hander.obtainMessage(SHOW_RESULT, text));
  28. }
  29. private synchronized void startTest() {
  30. if (testRunnerThread != null
  31. && testRunnerThread.isAlive()) {
  32. testRunnerThread = null;
  33. }
  34. if (testRunnerThread == null) {
  35. testRunnerThread = new Thread(new TestRunner(this));
  36. testRunnerThread.start();
  37. } else {
  38. Toast.makeText(this,
  39. "Test is still running",
  40. Toast.LENGTH_SHORT).show();
  41. }
  42. }
  43. public Handler hander = new Handler() {
  44. public void handleMessage(Message msg) {
  45. switch (msg.what) {
  46. case SHOW_RESULT:
  47. resultVIEw.setText(msg.obj.toString());
  48. break;
  49. case ERROR_FIND:
  50. messageVIEw.append(msg.obj.toString());
  51. barVIEw.setBackgroundColor(Color.RED);
  52. break;
  53. default:
  54. break;
  55. }
  56. }
  57. };
  58. class TestRunner implements Runnable, TestListener {
  59. private Activity parentActivity;
  60. private int testCount;
  61. private int errorCount;
  62. private int failureCount;
  63. public TestRunner(Activity parentActivity) {
  64. this.parentActivity = parentActivity;
  65. }
  66. @Override
  67. public void run() {
  68. testCount = 0;
  69. errorCount = 0;
  70. failureCount = 0;
  71. ExampleSuite suite = new ExampleSuite();
  72. androidTestRunner testRunner = new androidTestRunner();
  73. testRunner.setTest(suite);
  74. testRunner.addTestListener(this);
  75. testRunner.setContext(parentActivity);
  76. testRunner.runTest();
  77. }
  78. @Override
  79. public void addError(Test test, Throwable t) {
  80. errorCount++;
  81. showMessage(t.getMessage() + "\n");
  82. }
  83. @Override
  84. public void addFailure(Test test, AssertionFailedError t) {
  85. failureCount++;
  86. showMessage(t.getMessage() + "\n");
  87. }
  88. @Override
  89. public void endTest(Test test) {
  90. showResult(getResult());
  91. }
  92. @Override
  93. public void startTest(Test test) {
  94. testCount++;
  95. }
  96. private String getResult() {
  97. int successCount = testCount - failureCount - errorCount;
  98. return "Test:" + testCount + " Success:" + successCount + " Failed:" + failureCount + " Error:" + errorCount;
  99. }
  100. }
  101. }

第四步:修改androidManifest.XML,加入,不然會提示找不到androidTestRunner,這裡需要注意是這句話是放在applications下面的,我一開始也不知道,放錯了地方,浪費了不少時間

XML代碼

  1. XML version="1.0" encoding="utf-8"?>
  2. <manifest XMLns:android="http://schemas.Android.com/apk/res/android"
  3. package="com.test.sample"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
  7. <activity android:name=".TestActivity"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <action android:name="android.intent.action.MAIN" />
  11. <category android:name="android.intent.category.LAUNCHER" />
  12. intent-filter>
  13. activity>
  14. <uses-library android:name="android.test.runner" />
  15. application>
  16. <uses-sdk android:minSdkVersion="4" />
  17. manifest>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved