Chuyển đến nội dung

Bài 33 · Tools and Ecosystem

Testing in Scala: munit, ScalaTest and ScalaCheck

Test Scala 3 code with munit and ScalaTest: assertions, exceptions, async tests, fixtures, property-based testing with ScalaCheck, and how pure functions make tests simple.

Scala's emphasis on immutable data and pure functions pays off when you write tests. A pure function needs no setup and no mocks: you call it with inputs and check the output. This lesson shows the main testing libraries, how to organize tests, and how to go beyond hand-picked examples with property-based testing.

None of these libraries run on this site, so the Scala code is read-only. Set them up with sbt as shown in sbt and Project Setup. The runnable examples at the end are Java and Kotlin stand-ins that demonstrate the same ideas.

Setting up munit

munit is small, fast and the default choice for new Scala 3 projects. Add it to build.sbt:

SCALA
libraryDependencies += "org.scalameta" %% "munit" % "1.0.2" % Test

Tests live in src/test/scala. A suite is a class that extends munit.FunSuite:

SCALA
class StringUtilsSuite extends munit.FunSuite:

  def slugify(s: String): String =
    s.trim.toLowerCase.replaceAll("[^a-z0-9]+", "-").stripPrefix("-").stripSuffix("-")

  test("slugify lowercases and joins words with dashes") {
    assertEquals(slugify("Hello Scala World"), "hello-scala-world")
  }

  test("slugify removes punctuation at the edges") {
    assertEquals(slugify("  --Hello, World!--  "), "hello-world")
  }

  test("empty input gives empty slug") {
    assertEquals(slugify(""), "")
  }

Run everything with sbt test, one suite with sbt "testOnly *StringUtilsSuite", and re-run on every change with sbt ~test.

A good test

Clear name Says what behavior is checked.
Small One idea per test.
Repeatable Same result on every run.
Fast Milliseconds, not seconds.
1 / 2

Assertions

SCALA
class AssertionsSuite extends munit.FunSuite:

  test("equality with a helpful failure message") {
    assertEquals(List(1, 2, 3).map(_ * 2), List(2, 4, 6))
  }

  test("conditions") {
    assert(List(1, 2, 3).contains(2))
    assertNotEquals(1 + 1, 3)
  }

  test("doubles need a tolerance") {
    assertEqualsDouble(0.1 + 0.2, 0.3, 1e-9)
  }

  test("expected exceptions") {
    val e = intercept[NumberFormatException]("abc".toInt)
    assert(e.getMessage.contains("abc"))
  }

assertEquals checks that the two values have compatible types, which catches mistakes like comparing a List[Int] to a Vector[Int] by accident. Always put the obtained value first and the expected value second, so the failure output reads correctly.

Floating-point values are not exact (0.1 + 0.2 == 0.3 is false), which is why assertEqualsDouble takes a tolerance.

Testing pure functions and ADTs

Test data created from case classes (Case Classes) and ADTs compares by value, so assertions are direct:

SCALA
enum Expr:
  case Num(v: Double)
  case Add(l: Expr, r: Expr)

def eval(e: Expr): Double = e match
  case Expr.Num(v) => v
  case Expr.Add(l, r) => eval(l) + eval(r)

class EvalSuite extends munit.FunSuite:
  import Expr.*

  test("a number evaluates to itself") {
    assertEquals(eval(Num(4)), 4.0)
  }

  test("addition is evaluated recursively") {
    assertEquals(eval(Add(Num(1), Add(Num(2), Num(3)))), 6.0)
  }

Testing a function that returns Option or Either is just as simple: assertEquals(parseAge("abc"), Left("'abc' is not a number")). This is a strong reason to model failure as values (Option, Either and Try): the failure case is as easy to test as the success case.

Fixtures

Share setup with a fixture. munit's FunFixture creates a fresh resource for each test and cleans it up afterwards:

SCALA
class TempFileSuite extends munit.FunSuite:

  val tempFile = FunFixture[java.nio.file.Path](
    setup = _ => java.nio.file.Files.createTempFile("test", ".txt"),
    teardown = path => java.nio.file.Files.deleteIfExists(path)
  )

  tempFile.test("can write and read a file") { path =>
    java.nio.file.Files.writeString(path, "hello")
    assertEquals(java.nio.file.Files.readString(path), "hello")
  }

For a resource shared by the whole suite (a database container, a server), use beforeAll/afterAll or Fixture with beforeAll.

Asynchronous tests

A test can return a Future; munit waits for it:

SCALA
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

class AsyncSuite extends munit.FunSuite:
  test("a future is awaited") {
    Future(21 * 2).map(result => assertEquals(result, 42))
  }

This avoids Await in tests (see Futures and Promises). For IO and ZIO, use the companion libraries munit-cats-effect and zio-test.

ScalaTest

ScalaTest is older and has many styles. The AnyFunSuite style looks like munit, and the Matchers trait adds a readable should syntax:

SCALA
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

class ListSpec extends AnyFunSuite with Matchers:
  test("sum of a list") {
    List(1, 2, 3).sum shouldBe 6
  }
  test("filtering") {
    List(1, 2, 3, 4).filter(_ % 2 == 0) should contain theSameElementsAs List(2, 4)
  }
  test("failing code") {
    an [IllegalArgumentException] should be thrownBy require(false, "boom")
  }

Dependency: "org.scalatest" %% "scalatest" % "3.2.19" % Test. Choose one library per project; munit for simplicity, ScalaTest if your team already uses it, zio-test in ZIO projects.

Property-based testing

Example-based tests check the inputs you thought of. Property-based testing states a rule that must hold for all inputs and lets the library generate hundreds of random ones, including nasty edge cases. ScalaCheck is the standard library, and munit integrates it:

SCALA
import org.scalacheck.Prop.forAll

class ListProperties extends munit.ScalaCheckSuite:

  property("reversing twice gives the original list") {
    forAll { (xs: List[Int]) =>
      xs.reverse.reverse == xs
    }
  }

  property("sorted list has the same length") {
    forAll { (xs: List[Int]) =>
      xs.sorted.length == xs.length
    }
  }

  property("sum is independent of the order") {
    forAll { (xs: List[Int]) =>
      xs.sum == xs.reverse.sum
    }
  }

Add "org.scalameta" %% "munit-scalacheck" % "1.0.0" % Test. When a property fails, ScalaCheck shrinks the input to a small counterexample such as List(0, -1), which makes the bug easy to understand. Good properties: round trips (decode(encode(x)) == x), idempotence (sort(sort(xs)) == sort(xs)), and invariants (total price is never negative).

flowchart LR
    G["Generate random inputs"] --> R["Run property"]
    R -->|"holds"| N["Next input"]
    N --> G
    R -->|"fails"| S["Shrink to a minimal counterexample"]
    S --> F["Report failure"]

Mocks and test doubles

Pure code needs none. For code that talks to a database or HTTP service, pass the dependency as a trait parameter and give the test a simple fake implementation:

SCALA
trait Clock:
  def now(): java.time.Instant

class FixedClock(instant: java.time.Instant) extends Clock:
  def now() = instant

def isExpired(expires: java.time.Instant, clock: Clock): Boolean =
  clock.now().isAfter(expires)

A hand-written fake is usually clearer than a mocking framework (Mockito works with Scala when you really need it).

Test habits that pay off

  • Name tests as sentences describing behavior.
  • Test edge cases: empty collection, zero, negative, very large, None/Left.
  • Keep side effects out of the core so the core is testable without I/O.
  • Run tests on every change (~test) and in CI.
  • Do not test the framework or the language, test your logic.

Testing ideas in Java and Kotlin

These two examples are not Scala. The first is a tiny hand-written assertion harness in Kotlin that works like munit's test/assertEquals; the second is a seeded property check in Java.

Kotlin Kotlin: a mini test framework with assertEquals and intercept (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Java Java: a property check with a fixed seed (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Swapping obtained and expected, producing confusing failure messages.
  • Testing doubles with == instead of assertEqualsDouble.
  • Using Await and Thread.sleep in async tests; return the Future instead.
  • Shared mutable state between tests, which makes results depend on execution order.
  • Properties that restate the implementation, so they can never fail. Test a different angle, such as a round trip.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which munit assertion checks that code throws a particular exception?

    intercept[T] runs the code, expects an exception of type T, and returns it so you can inspect the message.
  2. 2. Why use assertEqualsDouble(0.1 + 0.2, 0.3, 1e-9)?

    0.1 + 0.2 is not exactly 0.3 in binary floating point, so the comparison needs a tolerance.
  3. 3. What does property-based testing do?

    ScalaCheck generates many random inputs for a stated property and reduces a failing input to a minimal counterexample.
  4. 4. What is the simplest way to test code that depends on the current time?

    Injecting the dependency as a parameter lets tests supply a deterministic implementation.

Summary

  • Pure functions, immutable data and values-as-errors (Option, Either) make Scala code very testable.
  • munit: test, assertEquals, assert, intercept, fixtures, Future-returning tests. ScalaTest offers matchers and many styles.
  • Property-based tests with ScalaCheck generate inputs and shrink counterexamples; use round-trip and invariant properties.
  • Replace dependencies by trait parameters and hand-written fakes.
  • Run tests continuously with sbt ~test and in CI.

Next: Java Interop and Libraries

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.