2016-12-28 72 views
6

我的應用程序依賴於兩個庫。他們都使用相同的庫'org.hamcrest:hamcrest-core',但內部版本不同。當兩個依賴關係對同一個庫具有內部依賴關係但在Android中具有不同版本時,gradle如何解決衝突?

androidTestCompile 'junit:junit:4.12' //(Depends on version 1.3) 
androidTestCompile 'org.mockito:mockito-core:1.10.19' //(Depends on version 1.1) 

由於兩個依賴都與Android instrumentation tests,應用程序成功地建立幷包括在構建更高版本 - 在這種情況下,1.3版。

但是,如果我用一個庫的主要應用和其他圖書館爲Android儀器測試如下:

compile 'junit:junit:4.12' 
androidTCompile 'org.mockito:mockito-core:1.10.19' 

我碰到下面的錯誤。

:app:prepareDebugAndroidTestDependencies 
Conflict with dependency 'org.hamcrest:hamcrest-core'. Resolved versions for app (1.3) and test app (1.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details. 

FAILED 

FAILURE: Build failed with an exception. 

* What went wrong: 
Execution failed for task ':app:prepareDebugAndroidTestDependencies'. 
> Dependency Error. See console for details. 

所以我去了例外中給出的鏈接。造成這種行爲的原因如下:

當儀器測試運行時,主APK和測試APK共享相同的類路徑。如果主APK和測試APK使用相同的庫(例如Guava),但使用不同版本,則Gradle構建將失敗。如果gradle沒有捕捉到這一點,那麼在測試和正常運行期間(包括其中一個案例中的崩潰),您的應用可能會有不同的表現。

高達這一點我沒有任何問題,但我必須在下列情況下一個問題:)

1在下面的聲明中,只創建一個主APK,因爲當地的單元測試運行JVM,那麼爲什麼這會失敗,同樣的衝突的例外

compile 'junit:junit:4.12' 
testCompile 'org.mockito:mockito-core:1.10.19' 

2)如果上述失敗,所以這也應該失敗。但令人驚訝的是,這工作正常,並建立良好。

androidTestCompile 'junit:junit:4.12' 
testCompile 'org.mockito:mockito-core:1.10.19' 

我無法理解這種模糊性與gradle解決了Android依賴性。

回答

0

說明

據我瞭解,testCompile依賴性也適用於androidTestCompile。否則,您需要將junit包括兩次,一次用於testCompile,另一次用於androidTestCompile。考慮到這一點,你的情況很容易解釋:

1)testCompile包括androidTestCompile,所以這種情況顯然與你的問題中的第一個例子相同,所以它是有道理的失敗。

2)這裏的compile在任何地方都沒有提到,所以主APK沒有任何Hamcrest版本,因此主APK之間不會有衝突。

解決方案

same page you cited還說:

爲了使構建成功,只要確保兩者的APK使用相同的版本。如果錯誤是關於一個間接依賴(一個在build.gradle中沒有提到的庫),那麼只需要將新版本的依賴項添加到需要它的配置(「compile」或「androidTestCompile」)中即可。 (...)

所以爲了防止主測試的APK之間的衝突,可以明確說明你想要的版本測試的依賴,就像這樣:

compile 'junit:junit:4.12' 
androidTestCompile 'org.mockito:mockito-core:1.10.19' 
androidTestCompile 'org.hamcrest:hamcrest-core:1.3' 

注:

當然,我們很少有很好的理由將junit包含在主APK中。這個事實並不會使問題失效,因爲除了junit之外,其他主要和測試版APK之間還有很多其他依賴關係,支持庫最有可能。