問題
在使用mockito和junit進行單元測試時候,編譯出現了以下的錯誤:
Conflict with dependency 'org.hamcrest:hamcrest-core'. Resolved versions for app (1.1) and test app (1.3) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
分析
根據錯誤信息的網址,發現又這樣的說明
Gradle build will fail if the main APK and the test APK use the same library (e.g. Guava) but in different versions.
即引用了相同庫的不同版本導致的編譯不過。
再通過執行./gradlew :app:dependencies查看依賴,得到以下的返回信息:
testCompile - Classpath for compiling the test sources.
+--- junit:junit:4.12
| --- org.hamcrest:hamcrest-core:1.3
--- org.mockito:mockito-core:1.9.5
+--- org.hamcrest:hamcrest-core:1.1 -> 1.3
--- org.objenesis:objenesis:1.0
可以看到junit和mockito分別引用了 hamcrest-core 的1.3和1.1版本引起的問題
解決方案
根據錯誤提示,將junit版本降級或者mockito版本升級都可以,這里因為mockito2.0以后才使用hamcrest1.3版本,且mockito2.0還是beta的,將junit從4.12降級為4.10即可解決這個問題。