1

I was thinking this would work but it did not for me.

libraryDependencies += "org.json4s" %% "json4s-core" % "3.6.7" % "test"
libraryDependencies += "org.json4s" %% "json4s-core" % "3.7.0" % "compile"

Any idea?

Dangerous Scholar
  • 225
  • 1
  • 3
  • 12

1 Answers1

1

Test classpath includes compile classpath.

So create different subrojects for different versions of the dependency if you need that.

lazy val forJson4s370 = project
  .settings(
    libraryDependencies += "org.json4s" %% "json4s-core" % "3.7.0" % "compile"
  )

lazy val forJson4s367 = project
  .settings(
    libraryDependencies += "org.json4s" %% "json4s-core" % "3.6.7" % "test"
  )

If you don't want to create different subprojects you can try custom sbt configurations

https://www.scala-sbt.org/1.x/docs/Advanced-Configurations-Example.html


An exotic solution is to manage dependencies and compile/run code programmatically in the exceptional class. Then you can have dependencies/versions different from specified in build.sbt.

import java.net.URLClassLoader
import coursier.{Dependency, Module, Organization, ModuleName, Fetch}
import scala.reflect.runtime.universe
import scala.reflect.runtime.universe.Quasiquote
import scala.tools.reflect.ToolBox

val files = Fetch()
  .addDependencies(
    Dependency(Module(Organization("org.json4s"), ModuleName("json4s-core_2.13")), "3.6.7"),
  )
  .run()

val depClassLoader = new URLClassLoader(
  files.map(_.toURI.toURL).toArray,
  /*getClass.getClassLoader*/ null // ignoring current classpath
)

val rm = universe.runtimeMirror(depClassLoader)
val tb = rm.mkToolBox()
tb.eval(q"""
  import org.json4s._
  // some exceptional json4s 3.6.7 code 
  println("hi")
""")
// hi

build.sbt

libraryDependencies ++= Seq(
  scalaOrganization.value % "scala-compiler" % scalaVersion.value % "test",
  "io.get-coursier" %% "coursier" % "2.1.0-M7-39-gb8f3d7532" % "test",
  "org.json4s" %% "json4s-core" % "3.7.0" % "compile",
)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • 1
    First option to split tests in a separate module is probably the easiest and cleanest, nice trick. – Gaël J Nov 04 '22 at 08:25
  • https://stackoverflow.com/questions/75562485/nosuchmethoderror-scala-tools-nsc-settings-usejavacplscala-tools-nsc-settings https://stackoverflow.com/questions/75621915/reflection-to-call-method-that-had-its-name-changed-in-an-upgrade – Dmytro Mitin Apr 04 '23 at 07:23