能否在构建文件中引入同一依赖的不同版本用于测试?尝试失败求助
解决test与compile作用域依赖版本冲突的问题
问题根源
test作用域会自动继承compile作用域的所有依赖,当你为两个作用域声明同一依赖的不同版本时,sbt默认的依赖冲突解决策略(优先选择版本号更高的依赖)会让test环境也使用3.7.0版本,直接覆盖了你指定的3.6.7版本。
可行解决思路
1. 为test作用域的依赖添加强制生效标记
在test作用域的依赖声明后追加force(),强制该版本在test环境中优先生效,忽略compile传递过来的高版本:
libraryDependencies += "org.json4s" %% "json4s-core" % "3.7.0" % "compile" libraryDependencies += "org.json4s" %% "json4s-core" % "3.6.7" % "test" force()
2. 针对Test配置强制指定依赖版本
通过dependencyOverrides限定仅在Test配置下使用指定版本,不会影响compile作用域的依赖:
libraryDependencies += "org.json4s" %% "json4s-core" % "3.7.0" % "compile" libraryDependencies += "org.json4s" %% "json4s-core" % "3.6.7" % "test" dependencyOverrides in Test += "org.json4s" %% "json4s-core" % "3.6.7"
3. 验证配置是否生效
执行以下sbt命令,检查test作用域的依赖版本是否符合预期:
# 查看test类路径中的具体依赖版本 sbt "show test:dependencyClasspath" # 查看test作用域的依赖声明详情 sbt "show test:libraryDependencies"
内容的提问来源于stack exchange,提问作者Dangerous Scholar
相关产品推荐
相关产品推荐

