簡體   English   中英

Maven 2 - 測試和編譯中的不同依賴版本

[英]Maven 2 - different dependency versions in test and compile

我有一個依賴於 commons-httpclient [2.0](編譯)的項目。

我想寫一些 jbehave 測試 - jbehave-core 3.4.5 (test)。 這兩個依賴項都依賴於 commons-lang,但版本不同 - 1.0.1 和 2.5。

依賴

當我執行mvn package時,我在測試部分得到 [BUID FAILURE]。 我的測試用例在surefire-plugin output中有一個例外:

java.lang.NoSuchMethodError: org.apache.commons.lang.StringUtils.substringBeforeLast(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;

正如我在源代碼中查看的那樣——在 commons-lang 1.0.1 中——確實,沒有 StringUtils.substringBeforeLast(...) 方法。 為什么 maven 在測試中使用來自 commons-httpclient(編譯)而不是來自 jbehave-core 的 commons-lang?

我無法在 commons-httpclient 中排除這種沖突的依賴關系,因此它必須保持在編譯時。

那么如何解決這個問題 - 測試中的 commons-lang 2.5 版本和編譯時的 1.0.1 版本?

Maven 3:

Maven 3 將嘗試獲取最近的依賴項,有效確保編譯和測試階段僅使用編譯或測試范圍的依賴項之一。

(感謝 Vineet Reynolds)

Maven 2(舊):

嘗試使用不同的版本和范圍定義 2 個不同的<dependency>標記。 在依賴項中使用標簽<scope>test</scope>進行測試,使用<scope>compile</scope>進行編譯。

在 Maven 3 中,您可以通過在 groupId 后添加一個點來欺騙 maven

<dependency>
  <groupId>groupId.</groupId>
  <artifactId>artifactId</artifactId>
  <version>version1</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>groupId</groupId>
  <artifactId>artifactId</artifactId>
  <version>version2</version>
  <scope>compile</scope>
</dependency>

順序在這里很重要。 需要先測試,然后編譯。

<dependency>
  <groupId>groupId.</groupId>
  <artifactId>artifactId</artifactId>
  <version>version1</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>groupId</groupId>
  <artifactId>artifactId</artifactId>
  <version>version2</version>
  <scope>compile</scope>
</dependency>

在 pom.xml 中添加一個點不起作用。 被轉換為斜線,這反過來生成了不正確的 URL。 有沒有其他方法可以做到這一點

有兩個不同的版本來編譯和測試依賴是一個非常糟糕的主意:

您的非測試代碼可能依賴於較新的 JAR 的行為,並且在使用較舊的 JAR 的類時會失敗。 當您在測試中使用舊版 JAR 時,舊版 JAR 會導致非測試代碼失敗。

否則,您可以在任何地方使用舊的 JAR,使用相同的版本...如果您將兩個 JAR 版本都放入您的類路徑,您將無法知道在運行測試時會選擇哪一個。 這也是個壞主意。

因此,您應該對相同的 JAR 版本依賴性進行非測試和測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM