The Scala Toolkit

How to test exceptions?

Language

You can require the entire toolkit in a single line:

//> using toolkit latest

MUnit, being a testing framework, is only available in test files: files in a test directory or ones that have the .test.scala extension. Refer to the Scala CLI documentation to learn more about the test scope.

Alternatively, you can require just a specific version of MUnit:

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

In your build.sbt file, you can add the dependency on toolkit-test:

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

Here the Test configuration means that the dependency is only used by the source files in src/test.

Alternatively, you can require just a specific version of MUnit:

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

In your build.sc file, you can add a test object extending Tests and TestModule.Munit:

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

Alternatively, you can require just a specific version of MUnit:

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

Intercepting an exception

In a test, you can use intercept to check that your code throws an exception.

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)
    }
  }

The type parameter of the intercept assertion is the expected exception. Here it is NoSuchFileException. The body of the intercept assertion contains the code that should throw the exception.

The test passes if the code throws the expected exception and it fails otherwise.

The intercept method returns the exception that is thrown. You can check more assertions on it.

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

You can also use the more concise interceptMessage method to test the exception and its message in a single assertion. Learn more about it in the MUnit documentation.

Contributors to this page: