ScalaTest
ScalaTest is the older and larger of the two test frameworks: one library with a style for every taste, from a plain function suite to a specification written as a sentence. The style a new project usually picks is AnyFunSuite, which is the same shape as MUnit, with Matchers adding the shouldBe family on top.
A suite in the function style
The suite extends AnyFunSuite and mixes in Matchers. Each test block holds one shouldBe or one assert, and the runner lists the tests it ran, then the totals. The file name ends in .test.scala here too:
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
CalcSpec.test.scala
//> using test.dep org.scalatest::scalatest::3.2.19
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
class CalcSpec extends AnyFunSuite with Matchers:
test("add adds two numbers") {
Calc.add(2, 3) shouldBe 5
}
test("divide keeps the quotient") {
Calc.divide(10, 2) shouldBe 5
}
test("divide by zero throws") {
val error = intercept[IllegalArgumentException] {
Calc.divide(1, 0)
}
error.getMessage shouldBe "division by zero"
}
test("a boolean assertion") {
assert(Calc.add(1, 1) == 2)
}
scala-cli test --server=false .
CalcSpec:
- add adds two numbers
- divide keeps the quotient
- divide by zero throws
- a boolean assertion
Total number of tests run: 4
Suites: completed 1, aborted 0
Tests: succeeded 4, failed 0, canceled 0, ignored 0, pending 0
All tests passed.
The report is longer than the MUnit one because ScalaTest names each test as it passes. The line the quote leaves out is Run completed in ..., whose duration changes on every run; the runner also prints a hint that ScalaTest 3.2.20 is available, since the dependency above names 3.2.19. A project pins the version it has tested and reads the hint as a reminder, not as an error.
Matchers against assertions
shouldBe reads as a sentence and, when it fails, prints the value with a diff. shouldEqual is the same comparison without the type check, and should contain works on a collection. A plain assert is still there for a condition that is easier to write than to phrase:
Calc.add(2, 3) shouldBe 5
List(1, 2, 3) should contain(2)
assert(Calc.add(1, 1) == 2)
The choice between the two frameworks is a choice of vocabulary, not of power: both run under the same runners, both report a failure with its line, and both can be mixed into a build. A team picks one for new suites and keeps the other where it already is.
Related
- MUnit: the framework of the previous lesson, with assertEquals instead of matchers.
- ScalaCheck properties: properties that run on either framework, or on their own.
- JUnit 5: the Java framework both Scala libraries report through, and the one a mixed project keeps for its Java tests.
- Common errors: the messages a red test run prints, and what each one means.
Автор статьи: Arthur Isaev