您可以在單一行中要求整個工具組
//> 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
物件,延伸 Tests
和 TestModule.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"
執行測試
您可以使用單一指令執行所有測試套件。
使用 Scala CLI,下列指令會執行 example
資料夾中的所有測試
scala-cli test example
# Compiling project (test, Scala 3.2.1, JVM)
# Compiled project (test, Scala 3.2.1, JVM)
# MyTests:
# + sum of two integers 0.009s
在 sbt shell 中,下列指令會執行 example
專案的所有測試
sbt:example> example/test
# MyTests:
# + sum of two integers 0.006s
# [info] Passed: Total 1, Failed 0, Errors 0, Passed 1
# [success] Total time: 0 s, completed Nov 11, 2022 12:54:08 PM
在 Mill 中,下列指令會執行 example
模組的所有測試
./mill example.test.test
# [71/71] example.test.test
# MyTests:
# + sum of two integers 0.008s
印在主控台中的測試報告會顯示每個測試的狀態。測試名稱前的 +
符號表示測試已成功通過。
新增並執行一個失敗的測試,看看失敗的樣子
test("failing test") {
val obtained = 2 + 3
val expected = 4
assertEquals(obtained, expected)
}
test("failing test") {
val obtained = 2 + 3
val expected = 4
assertEquals(obtained, expected)
}
# MyTests:
# + sum of two integers 0.008s
# ==> X MyTests.failing test 0.015s munit.ComparisonFailException: ./example/MyTests.test.scala:13
# 12: val expected = 4
# 13: assertEquals(obtained, expected)
# 14: }
# values are not the same
# => Obtained
# 5
# => Diff (- obtained, + expected)
# -5
# +4
# at munit.Assertions.failComparison(Assertions.scala:274)
以 ==> X
開頭的行表示名為 failing test
的測試失敗。下列行會顯示測試失敗的位置和原因。這裡顯示取得的值為 5,但預期為 4。