Android中的Junit測試

來源:互聯網
上載者:User

標籤:android   style   c   class   blog   code   

  在開發中Junit測試可以很方便的協助開者儘可能早的發現並處理問題,而且使用也非常簡單,只需要匯入Junit測試相關的jar包並建立測試類別,就可以對業務功能進行測試,而不用為了測試在代碼中添加輸出語句把代碼搞得面目全非。需要注意的是,編寫的測試方法只能是public void並且無參,在測試方法中就可以為所欲為了。

@Testpublic void testAdd(){    Demo d = new Demo();    System.out.println(d.add(1,2,3));}

  在Android環境下的測試似乎不太方便了,要編寫測試類別還要在應用項目配置中配置測試。好在google為大家提供了adtIntegration Environment,這個問題也不是問題了。
  接下來,看看一個Android項目做Junit測試的配置步驟:
  1、在項目的AndroidManifest.xml檔案中找到<application></application>節,在其中添加:

  <uses-library android:name="android.test.runner" />

 

  2、在項目的AndroidManifest.xml檔案中找到<manifest></manifest>節,在其中添加:

  <intent-filter>      <action android:name="android.intent.action.MAIN" />      <category android:name="android.intent.category.LAUNCHER" />  </intent-filter>

  3、建立一個測試類別,繼承AndroidTestCase,在其中編寫測試方法。如:

    public void testGetFirstName() throws Exception {        PersonService ps = new PersonService();        ps.getFirstName();    }    public void testCacl() throws Exception {        PersonService ps = new PersonService();        Assert.assertEquals(2, ps.calc());    }

  4、最後就可以runas -> Android JUnit Test,Junit視窗會顯示紅條或綠條,Console中看到一些資訊,諸如:

[2014-05-26 17:04:47 - SlideDemo] ------------------------------[2014-05-26 17:04:47 - SlideDemo] Android Launch![2014-05-26 17:04:47 - SlideDemo] adb is running normally.[2014-05-26 17:04:47 - SlideDemo] Performing android.test.InstrumentationTestRunner JUnit launch[2014-05-26 17:04:47 - SlideDemo] Automatic Target Mode: using existing emulator ‘emulator-5554‘ running compatible AVD ‘XT531‘[2014-05-26 17:04:47 - SlideDemo] Uploading SlideDemo.apk onto device ‘emulator-5554‘[2014-05-26 17:04:48 - SlideDemo] Installing SlideDemo.apk...[2014-05-26 17:04:49 - SlideDemo] Success![2014-05-26 17:04:49 - SlideDemo] Launching instrumentation android.test.InstrumentationTestRunner on emulator-5554[2014-05-26 17:04:50 - SlideDemo] Sending test information to Eclipse[2014-05-26 17:04:50 - SlideDemo] Test run finished

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.