如何在集成测试和单元测试之间共享代码

Moj*_*ojo 1 scala sbt

对于我的测试,我创建了一个对象,其中包含我所有的案例类(即我的生成器)的任意实例:


object Generators
    extends
    FooGen
  {


  def sample[A](implicit gen: Gen[A]): A =
    gen.sample.getOrElse(sys.error(s"Could not generate instance with $gen"))

  implicit def arb[A](implicit g: Gen[A]): Arbitrary[A] = Arbitrary(g)

}

trait FooGen { this: GenUtils =>

  implicit val fooGen: Gen[Foo] = gen[Foo]

}

Run Code Online (Sandbox Code Playgroud)

这当前位于我的 /test 文件夹下,因为我需要它为我的单元测试生成我的案例类的任意实例。但现在我想创建一些集成测试,这些测试将在我的 /it 文件夹下。将 /test 文件夹中的此生成器文件与 /it 文件夹中的测试共享的最佳方法是什么?

我的所有案例类都会有很多这样的生成器,所以我不想复制代码,这就是我问的原因。

Mar*_*lic 5

基于gilad hoch 的回答try

IntegrationTest / dependencyClasspath := 
  (IntegrationTest / dependencyClasspath).value ++ (Test / exportedProducts).value
Run Code Online (Sandbox Code Playgroud)

例如你build.sbt可能看起来像

lazy val root = (project in file("."))
  .configs(IntegrationTest)
  .settings(
    Defaults.itSettings,
    libraryDependencies += scalaTest % "it,test",
    IntegrationTest / dependencyClasspath :=
      (IntegrationTest / dependencyClasspath).value ++ (Test / exportedProducts).value
  )
Run Code Online (Sandbox Code Playgroud)

和目录结构

??? it
?   ??? scala
?       ??? example
?           ??? GoodbyeSpec.scala
??? main
?   ??? scala
?       ??? example
?           ??? Hello.scala
??? test
    ??? scala
        ??? example
            ??? FooGen.scala
            ??? HelloSpec.scala
Run Code Online (Sandbox Code Playgroud)

所以现在FooGen.scala可以从GoodbyeSpec.scala.

另一种选择是创建一个多项目构建并将常见的测试代码分解到它自己的项目中,也许test-common,然后让主项目依赖

lazy val core = (project in file("core"))
  .dependsOn(testCommon)
  .settings(
    // other settings
  )

lazy val testCommon = (project in file("testCommon"))
  .settings(
    // other settings
  )
Run Code Online (Sandbox Code Playgroud)