Scala Testing with munit
Automated tests check that your code does what you think it does — today, and after every future change. munit is a small, fast test library for Scala with clear failure messages and colourful diffs. It works with scala-cli, sbt and Mill, and it is the library the Scala Center recommends for getting started.
Setting up munit
With scala-cli, add a test dependency and name your test files *.test.scala:
// project.scala
//> using scala 3.7.1
//> using test.dep org.scalameta::munit:1.1.1With sbt, add it to build.sbt:
libraryDependencies += "org.scalameta" %% "munit" % "1.1.1" % TestThe code under test
// Cart.scala
case class Item(name: String, priceCents: Long, qty: Int)
object Cart:
def total(items: List[Item]): Long =
items.map(i => i.priceCents * i.qty).sum
def applyCoupon(total: Long, code: String): Either[String, Long] = code match
case "TENOFF" => Right(math.max(0, total - 1000))
case "HALF" => Right(total / 2)
case other => Left(s"unknown coupon: $other")Writing a test suite
A test suite is a class that extends munit.FunSuite. Each test("name") { … } block is one test case.
// Cart.test.scala
class CartSuite extends munit.FunSuite:
val basket = List(Item("pen", 150, 4), Item("pad", 300, 1))
test("total multiplies price by quantity"):
assertEquals(Cart.total(basket), 900L)
test("empty cart costs nothing"):
assertEquals(Cart.total(Nil), 0L)
test("TENOFF never goes below zero"):
assertEquals(Cart.applyCoupon(500, "TENOFF"), Right(0L))
test("unknown coupons are rejected"):
val result = Cart.applyCoupon(900, "FREE")
assert(result.isLeft, "expected a Left")
assertEquals(result.left.toOption, Some("unknown coupon: FREE"))
test("bad quantities are a bug"):
intercept[IllegalArgumentException]:
require(basket.forall(_.qty > 0), "quantity must be positive")
throw IllegalArgumentException("simulated failure")scala test .Compiling project (test, Scala 3.7.1, JVM (21))
Compiled project (test, Scala 3.7.1, JVM (21))
CartSuite:
+ total multiplies price by quantity 0.011s
+ empty cart costs nothing 0.001s
+ TENOFF never goes below zero 0.001s
+ unknown coupons are rejected 0.002s
+ bad quantities are a bug 0.001s
Assertions
| Assertion | Checks |
|---|---|
assert(cond, clue) |
a condition is true |
assertEquals(obtained, expected) |
two values are equal (types must match) |
assertNotEquals(a, b) |
two values differ |
assertEqualsDouble(a, b, delta) |
doubles are within delta |
assertNoDiff(a, b) |
multi-line strings, ignoring whitespace differences |
intercept[E] { … } |
the block throws an E |
interceptMessage[E]("msg") { … } |
… with exactly this message |
fail("msg") |
fail unconditionally |
Reading a failure
When an assertion fails, munit shows the test name, the source line and a diff of obtained vs. expected values:
scala test .CartSuite:
==> X CartSuite.total multiplies price by quantity 0.015s munit.ComparisonFailException: Cart.test.scala:6
5: test("total multiplies price by quantity"):
6: assertEquals(Cart.total(basket), 950L)
values are not the same
=> Obtained
900
=> Diff (- obtained, + expected)
-900
+950
+ empty cart costs nothing 0.001s
+ TENOFF never goes below zero 0.001s
+ unknown coupons are rejected 0.001s
+ bad quantities are a bug 0.001s
The idea without a library
munit's core idea is simple: run named checks and report the ones that fail. This tiny hand-made harness (standard library only) shows the same flow, so you can see the output pattern right here:
case class Item(name: String, priceCents: Long, qty: Int)
object Cart:
def total(items: List[Item]): Long = items.map(i => i.priceCents * i.qty).sum
var failures = 0
def test(name: String)(body: => Unit): Unit =
try
body
println(s" + $name")
catch case e: AssertionError =>
failures += 1
println(s" X $name: ${e.getMessage}")
def assertEquals[A](obtained: A, expected: A): Unit =
if obtained != expected then throw AssertionError(s"obtained $obtained, expected $expected")
@main def run(): Unit =
val basket = List(Item("pen", 150, 4), Item("pad", 300, 1))
println("CartSuite:")
test("total multiplies price by quantity")(assertEquals(Cart.total(basket), 900L))
test("empty cart costs nothing")(assertEquals(Cart.total(Nil), 0L))
test("deliberately wrong expectation")(assertEquals(Cart.total(basket), 950L))
println(s"${3 - failures} passed, $failures failed")CartSuite:
+ total multiplies price by quantity
+ empty cart costs nothing
X deliberately wrong expectation: obtained 900, expected 950
2 passed, 1 failed
Fixtures and async tests
- Setup and teardown: override
beforeEach/afterEach, or useFunFixtureto create a fresh resource (a temp directory, an in-memory database) for every test. - Async code: if a test body returns a
Future, munit waits for it automatically:
test("loads a user asynchronously"):
UserService.load(42).map(user => assertEquals(user.name, "Ada"))- Selecting tests:
test("slow one".ignore)skips a test;test("this one".only)runs only that test while you debug.
What makes a good test?
| Guideline | Why |
|---|---|
| One behaviour per test | a failure points at exactly one problem |
| Descriptive names | the name reads like a specification |
| Test edge cases | empty lists, zero, negative numbers, unknown inputs |
| Keep tests deterministic | no real time, randomness or network |
| Test pure functions first | they need no setup and run in microseconds |
Tip: Writing your logic as pure functions on case classes (as this course encourages) makes testing almost effortless: call the function, compare the result.
Test yourself
Which class does a munit test suite extend?
munit.Testmunit.FunSuiteorg.junit.TestCasescala.Test
Which assertion checks that a block throws an IllegalArgumentException?
assertThrows(...)intercept[IllegalArgumentException] { ... }assertEquals(e, IllegalArgumentException)expect[IllegalArgumentException]
How does scala-cli recognise test files by default?
- Files ending in
.test.scala(or in atestdirectory) - Any file with
Testin its name - Files under
src/main - It does not run tests