0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

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

  1. ScalaTest Styles
  2. Matchers
  3. Property-Based Testing
  4. Mocking and Fixtures
← Back to Scala for Backend Engineering & Functional Programming