Mocking and Fixtures
Test setup.
Mocking and Fixtures is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
}
}BeforeAndAfter
Mix in BeforeAndAfter to run code before and after each test using before { } and after { } blocks.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.BeforeAndAfter
class DbSpec extends AnyFlatSpec with Matchers with BeforeAndAfter {
var counter = 0
before { counter = 10 }
after { counter = 0 }
"counter" should "be initialized" in {
counter shouldBe 10
}
}BeforeAndAfterAll
For expensive resources shared across all tests in a suite (a database connection, an embedded server), use BeforeAndAfterAll with beforeAll and afterAll.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.BeforeAndAfterAll
class ServerSpec extends AnyFlatSpec with BeforeAndAfterAll {
override def beforeAll(): Unit = println("start server")
override def afterAll(): Unit = println("stop server")
"server" should "respond" in {
assert(true)
}
}Loan-Fixture Pattern
The loan pattern passes a freshly built resource to the test body and guarantees cleanup in a finally, even if the test fails.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class FileSpec extends AnyFlatSpec with Matchers {
def withBuffer(test: StringBuilder => Any): Unit = {
val buf = new StringBuilder("init")
try test(buf)
finally buf.clear()
}
"a buffer" should "start with init" in withBuffer { buf =>
buf.toString shouldBe "init"
}
}Why Mocking?
A mock is a stand-in for a real dependency (a database, an HTTP client) so a unit test stays fast and deterministic. You control what the mock returns and verify how it was called.
Adding Mockito
ScalaTest integrates with Mockito via scalatestplus. Add the dependency and mix in MockitoSugar.
libraryDependencies += "org.scalatestplus" %% "mockito-5-10" % "3.2.18.0" % TestStubbing a Method
Create a mock and program its behavior with when(...).thenReturn(...). The test then exercises code that depends on it.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar
import org.mockito.Mockito.when
trait Repo { def find(id: Int): String }
class RepoSpec extends AnyFlatSpec with Matchers with MockitoSugar {
"a repo" should "return stubbed value" in {
val repo = mock[Repo]
when(repo.find(1)).thenReturn("Alice")
repo.find(1) shouldBe "Alice"
}
}Verifying Interactions
Beyond return values, you can verify a method was called the expected number of times with verify.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.mockito.MockitoSugar
import org.mockito.Mockito.{verify, times}
trait Logger { def log(msg: String): Unit }
class LogSpec extends AnyFlatSpec with MockitoSugar {
"a service" should "log once" in {
val logger = mock[Logger]
logger.log("hi")
verify(logger, times(1)).log("hi")
}
}Mocks vs Stubs vs Fakes
Terminology:
- Stub: returns canned answers.
- Mock: also lets you verify interactions.
- Fake: a lightweight working implementation (e.g. in-memory repo).
Prefer fakes or real objects when simple; mock only true external dependencies.
Keeping Tests Isolated
Fixtures and mocks aim for one goal: each test runs in a known, independent state. Reset shared mutable state before each test, and avoid sharing mutable fixtures across tests to prevent flaky, order-dependent failures.
Quick Check
Test your knowledge of fixtures and mocking.
Recap
You learned fixtures and mocking:
- Fixtures: helper methods,
BeforeAndAfter,BeforeAndAfterAll, and the loan pattern. - Mocks (via MockitoSugar): stub with
when().thenReturn(), check calls withverify. - Prefer fakes for simple cases; mock external dependencies.
- Keep every test isolated and order-independent.
Frequently asked questions
Is the “Mocking and Fixtures” lesson free?
Yes — the full text of “Mocking and Fixtures” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Mocking and Fixtures”?
Test setup. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking and Fixtures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- ScalaTest Styles
- Matchers
- Property-Based Testing
- Mocking and Fixtures