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"

攔截例外

在測試中,您可以使用 intercept 檢查您的程式碼是否擲回例外。

import java.nio.file.NoSuchFileException

class FileTests extends munit.FunSuite {
  test("read missing file") {
    val missingFile = os.pwd / "missing.txt"
    
    intercept[NoSuchFileException] { 
      os.read(missingFile)
    }
  }
}
import java.nio.file.NoSuchFileException

class FileTests extends munit.FunSuite:
  test("read missing file") {
    val missingFile = os.pwd / "missing.txt"
    intercept[NoSuchFileException] {
      // the code that should throw an exception
      os.read(missingFile)
    }
  }

intercept 斷言的類型參數為預期的例外。這裡是 NoSuchFileExceptionintercept 斷言的主體包含應該擲回例外的程式碼。

如果程式碼擲回預期的例外,則測試通過,否則失敗。

intercept 方法傳回擲回的例外。您可以在其上檢查更多斷言。

val exception = intercept[NoSuchFileException](os.read(missingFile))
assert(clue(exception.getMessage).contains("missing.txt"))

您也可以使用更簡潔的 interceptMessage 方法在單一斷言中測試例外及其訊息。在 MUnit 文件 中深入了解它。

此頁面的貢獻者