Scala Testing with Assert
Testing with assert is the practice of writing small checks that a program must pass. Each check states one behaviour the code must show.
Two asserts pass and then the pass line prints
Both conditions hold, so both asserts pass silently. The printed line proves they ran.
@main def main(): Unit =
assert(1 + 1 == 2)
assert(List(1, 2).length == 2)
println("addition and length pass")A label names each check
Each assert carries a label for the case it checks. The pass line prints only after both checks hold.
def double(x: Int): Int = x * 2
@main def main(): Unit =
assert(double(3) == 6, "double of 3")
assert(double(0) == 0, "double of 0")
println("double pass")Asserts check strings and sorting too
The uppercase check and the sorting check both hold. The pass line proves both ran.
@main def main(): Unit =
assert("Scala".toUpperCase == "SCALA")
assert(List(3, 1).sorted == List(1, 3))
println("string and sort pass")Example
def area(width: Int, height: Int): Int = width * height
@main def main(): Unit =
assert(area(3, 4) == 12, "3 by 4")
assert(area(0, 9) == 0, "zero width")
assert(area(5, 5) == 25, "square")
println("all area tests pass")Key points
- Assert: assert checks a condition and passes silently when it holds.
- Assert label: a second argument names the check, so a failure says what broke.
- Pass line: a test block prints a pass line after its asserts, proving they ran.
- One behaviour: each assert checks one behaviour, not several at once.
- Failing assert: a failed assert stops the program with an AssertionError.
In this example, area is tested with three cases. A normal rectangle, a zero width, and a square each get their own labelled assert. The pass line prints only after all three checks hold.
Note
a test block in this course always passes, so its stated output is the pass line.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does a passing assert itself print?