在Android開發中,測試是一個很少被提及的話題。在早期,Android並沒有一個很好 的測試框架,你也很難找到一個測試全面的優秀開源項目。隨着Android社區的成熟,出現了諸如Robotium,Robolectric等的 優秀測試框架。而Google也推出了自己的UI測試框架Espresso。
1.build.gradle中配置Espresso
apply plugin: 'com.android.application'
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
// Always show the result of every unit test, even if it passes.
testOptions.unitTests.all{
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
}
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
...
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
androidTestCompile 'com.android.support.test:runner:0.2'
}(這裏要注意的是,app版本和test版本要一致,比如一個v24.0.0,一個v22.0.0就會報錯!!)
2.點擊Gradle同步
3.由於我使用的是2.2.3版本的android studio,省去了在Build Variants窗口內的Test Artifact中選擇了"Unit Tests"這一步。
點擊test新建測試
注意有2個包,我一開始新建到下面報錯了,很奇怪,改到上面的目錄就沒事了。
4.編寫例子
5.點擊run,開啓手機會自己跑,很神奇,第一次跑可能有點慢哦,因爲在下什麼東西,後面再開就是秒跑啦。
參考鏈接http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0605/2999.html