Android單元測試基礎

最近項目組在嘗試引入單元測試,于是對單元測試進行一些基本的了解。

基本概念

維基百科的定義:單元測試(又稱為模塊測試, Unit Testing)是針對程序模塊(軟件設計的最小單位)來進行正確性檢驗的測試工作。程序單元是應用的最小可測試部件。在過程化編程中,一個單元就是單個程序、函數、過程等;對于面向對象編程,最小單元就是方法,包括基類(超類)、抽象類、或者派生類(子類)中的方法。

《軟件測試方法和技術》(朱少民 清華大學出版社 2005年7月第一版):單元測試是對軟件基本組成單元的測試。單元測試的對象是軟件設計的最小單位——模塊。很多參考書中將單元測試的概念誤導為一個具體函數或一個類的方法。一個最小的單元應該有明確的功能、性能定義、接口定義而且可以清晰地與其他單元區分開來。一個菜單、一個顯示界面或者能夠獨立完成的具體功能都可以是一個單元。某種意義上單元的概念已經擴展為組件(component)

對單元測試的中單元的概念,其實大家的理解不是很一致。我更傾向于《軟件測試方法和技術》的說法,單元測試的測試單元是具有明確的功能、性能定義、接口定義的模塊。

作用

關于單元測試的作用其實也是廣受爭議。

http://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort

配置

官網例子

http://developer.android.com/training/testing/start/index.html

dependencies {

// Required — JUnit 4 framework

testCompile ‘junit:junit:4.12’

// Optional — Mockito framework

testCompile ‘org.mockito:mockito-core:1.10.19’

}

dependencies {

androidTestCompile ‘com.android.support:support-annotations:23.0.1’

androidTestCompile ‘com.android.support.test:runner:0.4.1’

androidTestCompile ‘com.android.support.test:rules:0.4.1’

// Optional — Hamcrest library

androidTestCompile ‘org.hamcrest:hamcrest-library:1.3’

// Optional — UI testing with Espresso

androidTestCompile ‘com.android.support.test.espresso:espresso-core:2.2.1’

// Optional — UI testing with UI Automator

androidTestCompile ‘com.android.support.test.uiautomator:uiautomator-v18:2.1.1’

}

testCompile與androidTestCompile區別

在dependencies中,大家可以看到testCompile和androidTestCompile,讓人比較迷惑。實際上是測試使用的代碼路徑不同,testCompile用于src/test,測試Android環境無關的代碼,androidTestCompile用于src/androidTest,測試與Android Api相關的部分。

以下為stackoverflow上的答案,相對清晰。

Simply testCompile is the configuration for unit tests (those located in src/test) and androidTestCompile is used for the test api (that located in src/androidTest). Since you are intending to write unit tests, you should use testCompile.

Update: The main distinction between the two is the test sourceset runs in a regular Java JVM, whereas the androidTest sourceset tests run on an Android device (or an emulator).

JUnit

junit已經成為java單元測試的最普及的框架。

Mockito

Robolectric

參考資料:

來自: http://coderrobin.com/2016/01/15/Android單元測試/

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!