Gradle中的差異化構建

Harlber發表於2018-04-09

gradle的依賴構建配置項常見的在專案中有

  • compile 'com.github.bumptech.glide:glide:3.7.0'
  • debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.4'
  • releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'

一直沒有深究過這些構建方式間的差異 實際上還有

  • testCompile 'junit:junit:4.12'

  • androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 以及

  • providedCompile group: 'javax.servlet.jsp.jstl', name: 'jstl', version: '1.2'

  • runtime group: 'mysql', name: 'mysql-connector-java', version: '5.1.42

  • Apk(只在打包Apk包時依賴)

可以從資源和行為的方式將以上5中構建方式分為2類

  • compile testCompileandroidTestCompile

    以及

  • debugCompile,releaseCompile

compile:將依賴構建進專案中,引用資源的原始檔位於module-name/src/main/java/下,任何時候都會依賴,相對應的providedCompile:僅在編譯時依賴,執行時不依賴 runtime:僅在執行時依賴

testCompile:構建的是本地單元測試,測試源處於module-name/src/test/java/目錄下。 常見的,會在gradle中做如下配置

  dependencies {
   // Required -- JUnit 4 framework
   testCompile 'junit:junit:4.12'
   // Optional -- Mockito framework
   testCompile 'org.mockito:mockito-core:1.10.19'
}
複製程式碼

androidTestCompile:構建的是模擬器環境的單元測試,測試源處於module-name/src/androidTest/java/下。 常見的配置如下:

  dependencies {
    androidTestCompile 'com.android.support:support-annotations:24.0.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    // 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.2'
    // Optional -- UI testing with UI Automator
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}
複製程式碼

debugCompile 和 releaseCompile從行為上說和我們構建的環境相關,是debug還是release環境,區別是如果專案中依賴的模組僅僅宣告瞭debugCompile 那麼在構建release包的時候將編譯不通過,原因在於release的task不會將僅宣告debugCompile的依賴構建進工程,導致找不到依賴。

注意:Android Studio 3.X開始使用了新的指令,原來的很多被棄用了,總的來說是為了加快構建編譯速度。

最後說一下mock的問題,寫過單元測試的同學都知道,一件很痛苦的事是mock不到android package下的方法,導致單元測試無法進行。好在官方指了一條路,

Mockito

You can use a mocking framework to stub out external dependencies in your code, to easily test that your component interacts with a dependency in an expected way. By substituting Android dependencies with mock objects, you can isolate your unit test from the rest of the Android system while verifying that the correct methods in those dependencies are called. The Mockito mocking framework for Java (version 1.9.5 and higher) offers compatibility with Android unit testing. With Mockito, you can configure mock objects to return some specific value when invoked.

參考:

相關文章