android studio下gradle Robolectric單元測試配置html
1.Robolectricjava
Robolectric是一個基於junit之上的單元測試框架。它並不依賴於Android提供的測試功能,它使用了shadow objects而且運行測試於普通的工做站/服務器JVM,不像模擬器或設備須要dexing(Android dex編譯器將類文件編譯成Android設備上的Dalvik VM使用的格式),打包,部署和運行的過程,大大減小了測試執行的時間。android
參考:安卓單元測試相關概述http://www.cnblogs.com/droidpilot/archive/2012/04/27/2473291.htmlgit
2.下載as插件github
若是是android studio 0.8.9如下的版本,須要按照指示添加額外配置android-studio
https://github.com/evant/android-studio-unit-test-plugin服務器
3.編寫gradle 配置app
項目地址:https://github.com/JCAndKSolutions/android-unit-test框架
如下是配置的詳細說明maven
buildscript { repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { classpath 'com.android.tools.build:gradle:0.12.+' // classpath 'org.robolectric:robolectric-gradle-plugin:0.13.+’ //引用相關gradle插件 classpath 'com.github.jcandksolutions.gradle:android-unit-test:1.6.2' } } apply plugin: 'android-library' apply plugin: 'idea' idea { module { //設置測試類的輸出目錄 testOutputDir = file('build/test-classes') } } repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } //因爲android studiode 一個bug,必須把module的iml文件中的android sdk引用放到最下面 task pushDownJdkDependency { //這裏是待測試項目的iml文件名 def imlFile = file("library.iml") doLast { try { def parsedXml = (new XmlParser()).parse(imlFile) def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' } parsedXml.component[1].remove(jdkNode) //這裏是target sdk版本,只須要改數字就行 new Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': "Android API 19 Platform", 'jdkType': 'Android SDK']) def writer = new StringWriter() new XmlNodePrinter(new PrintWriter(writer)).print(parsedXml) imlFile.text = writer.toString() } catch (FileNotFoundException e) { // nop, iml not found } } } //在build以前修改iml文件 gradle.projectsEvaluated { preBuild.dependsOn(pushDownJdkDependency) } android { compileSdkVersion 19 buildToolsVersion '19.1.0' sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src/main/java'] res.srcDirs = ['res’] //指定測試文件所在目錄 androidTest.setRoot('src/test') } } defaultConfig { minSdkVersion 10 targetSdkVersion 19 versionCode 2 versionName "2.0.0" testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner" } } //應用插件 apply plugin: 'android-unit-test' dependencies { compile 'com.android.support:support-v4:19.1.0’ //注意,若是https://github.com/evant/android-studio-unit-test-plugin,此插件沒有安裝,則可能沒法識別testCompile語義 //junit:junit和org.robolectric:robolectric是必須項,其餘的項目根據實際引用添加 testCompile 'junit:junit:4.10' testCompile 'org.robolectric:robolectric:2.3' testDebugCompile 'org.debugonly.dependency' testFreeCompile 'Admob.jar' testCompile 'org.mockito:mockito-all:1.9.5' testCompile('com.squareup:fest-android:1.0.+') { exclude module: 'support-v4' } }
4.運行測試
直接在as的終端裏面執行:gradle test 或者./gradlew test 便可