Scala 工具組

如何管理測試的資源?

語言

您可以在單一行中要求整個工具組

//> using toolkit latest

MUnit 是一個測試架構,僅在測試檔案中可用:test 目錄中的檔案或具有 .test.scala 副檔名的檔案。請參閱 Scala CLI 文件 以瞭解更多有關測試範圍的資訊。

或者,你也可以只要求 MUnit 的特定版本

//> using dep org.scalameta::munit:1.0.0-M7

在你的 build.sbt 檔案中,你可以加入對 toolkit-test 的相依性

lazy val example = project.in(file("example"))
  .settings(
    scalaVersion := "3.2.2",
    libraryDependencies += "org.scala-lang" %% "toolkit-test" % "0.1.7" % Test
  )

這裡的 Test 組態表示相依性只會被 example/src/test 中的原始檔使用。

或者,你也可以只要求 MUnit 的特定版本

libraryDependencies += "org.scalameta" %% "munit" % "1.0.0-M7" % Test

在你的 build.sc 檔案中,你可以加入一個 test 物件,延伸 TestsTestModule.Munit

object example extends ScalaModule {
  def scalaVersion = "3.2.2"
  object test extends Tests with TestModule.Munit {
    def ivyDeps =
      Agg(
        ivy"org.scala-lang::toolkit-test:0.1.7"
      )
  }
}

或者,你也可以只要求 MUnit 的特定版本

ivy"org.scalameta::munit:1.0.0-M7"

FunFixture

在 MUnit 中,我們使用函式固定裝置以簡潔且安全的方式管理資源。FunFixture 為每個測試建立一個資源,確保每個測試都與其他測試隔離執行。

在測試套件中,你可以定義並使用 FunFixture 如下

class FileTests extends munit.FunSuite {
  val usingTempFile: FunFixture[os.Path] = FunFixture(
    setup = _ => os.temp(prefix = "file-tests"),
    teardown = tempFile => os.remove(tempFile)
  )
  usingTempFile.test("overwrite on file") { tempFile =>
    os.write.over(tempFile, "Hello, World!")
    val obtained = os.read(tempFile)
    assertEquals(obtained, "Hello, World!")
  }
}
class FileTests extends munit.FunSuite:
  val usingTempFile: FunFixture[os.Path] = FunFixture(
    setup = _ => os.temp(prefix = "file-tests"),
    teardown = tempFile => os.remove(tempFile)
  )
  usingTempFile.test("overwrite on file") { tempFile =>
    os.write.over(tempFile, "Hello, World!")
    val obtained = os.read(tempFile)
    assertEquals(obtained, "Hello, World!")
  }

usingTempFileFunFixture[os.Path] 型別的固定裝置。它包含兩個函式

  • setup 函式,TestOptions => os.Path 型別,建立一個新的暫存檔。
  • teardown 函式,os.Path => Unit 型別,刪除這個暫存檔。

我們使用 usingTempFile 固定裝置定義一個需要暫存檔的測試。請注意,測試的主體會將 tempFileos.Path 型別)作為參數。固定裝置會自動建立這個暫存檔,呼叫其 setup 函式,並在測試後呼叫 teardown 清除它。

在這個範例中,我們使用固定裝置管理一個暫存檔。一般來說,固定裝置可以管理其他類型的資源,例如暫存資料夾、資料庫中的暫存表格、與本機伺服器的連線等等。

撰寫 FunFixture

在某些測試中,您可能需要多個資源。您可以使用 FunFixture.map2 將兩個函式固定裝置組合成一個。

val using2TempFiles: FunFixture[(os.Path, os.Path)] =
  FunFixture.map2(usingTempFile, usingTempFile)

using2TempFiles.test("merge two files") {
  (file1, file2) =>
    // body of the test
}
val using2TempFiles: FunFixture[(os.Path, os.Path)] =
  FunFixture.map2(usingTempFile, usingTempFile)

using2TempFiles.test("merge two files") {
  (file1, file2) =>
    // body of the test
}

FunFixture[A]FunFixture[B] 上使用 FunFixture.map2 會傳回 FunFixture[(A, B)]

其他固定裝置

FunFixture 是建議的固定裝置類型,因為

  • 它很明確:每個測試都宣告它們需要的資源,
  • 它很安全:每個測試都獨立使用自己的資源。

為了更靈活,MUnit 包含其他類型的固定裝置:可重複使用的固定裝置、臨時固定裝置和非同步固定裝置。在 MUnit 文件 中深入了解它們。

此頁面的貢獻者