MUnit

A test is a program that calls the code and compares the answer with the one the specification names. MUnit is the small framework the Scala ecosystem uses most: a suite is a class that extends munit.FunSuite, a test is a named block inside it, and the runner prints one line per suite. It is a library, not a build tool, so the same suite runs under scala-cli, under sbt and in a continuous integration job.

The class under test and its suite

Calc is the code: three methods, one of which refuses a division by zero with an exception. The suite is a second file whose name ends in .test.scala, which is how the runner knows that the file belongs to the test scope. The directive at the top of the suite names MUnit 1.3.6, and test gives each block a name the report repeats:

calc.scala

object Calc: def add(a: Int, b: Int): Int = a + b def divide(a: Int, b: Int): Int = if b == 0 then throw new IllegalArgumentException("division by zero") else a / b def parse(text: String): Option[Int] = text.toIntOption

CalcSuite.test.scala

//> using test.dep org.scalameta::munit::1.3.6 class CalcSuite extends munit.FunSuite: test("adds two numbers") { assertEquals(Calc.add(2, 3), 5) } test("divides") { assertEquals(Calc.divide(10, 2), 5) } test("division by zero throws") { val error = intercept[IllegalArgumentException] { Calc.divide(1, 0) } assertEquals(error.getMessage, "division by zero") } test("parses a number and refuses a word") { assert(Calc.parse("42").contains(42)) assertEquals(Calc.parse("forty-two"), None) }

scala-cli test --server=false .

Test run CalcSuite started
CalcSuite: finished <TIME>
Test run CalcSuite finished: 0 failed, 0 ignored, 4 total <TIME>

The report counts the suite, not the tests: 0 failed, 0 ignored, 4 total. The two numbers that matter in a continuous integration job are the failed count and the exit status, and a red run ends with Error: munit tests failed. and status 1.

What a test body may assert

assertEquals compares two values and prints both, and their diff, when they differ. assert takes a boolean and is the tool for a condition that has no second value to show. intercept runs a block and returns the exception it throws, so the expected failure is part of the test rather than an error the runner reports:

val error = intercept[IllegalArgumentException] { Calc.divide(1, 0) } assertEquals(error.getMessage, "division by zero")

A block is the third form: intercept needs one because the call that throws must not run before it is wrapped, and assertEquals returns Unit. A test that must fail on purpose uses assert(condition) inside intercept, or munit.Assertions.fail with the message the failure should carry.

Related

Article author: Arthur Isaev