Mocking and Fixtures
Test setup.
Test Setup and Teardown
Many tests need shared fixtures: data or resources prepared before a test and cleaned up after. ScalaTest offers several ways to manage this without duplicating setup code.
Simple Fixture: Just a Method
The simplest fixture is a helper method that builds fresh state. Each test calls it, guaranteeing isolation.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class StackSpec extends AnyFlatSpec with Matchers {
def emptyStack(): scala.collection.mutable.Stack[Int] =
scala.collection.mutable.Stack.empty[Int]
"a stack" should "start empty" in {
emptyStack().size shouldBe 0
}
}All lessons in this course
- ScalaTest Styles
- Matchers
- Property-Based Testing
- Mocking and Fixtures