Skip to Content
Course content

226: Snapshot Testing for Scala Data Structures

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're overseeing a massive home renovation. You aren't just painting a wall; you're redesigning the entire floor plan, updating the electrical, and swapping out every fixture. If you tried to write a checklist of every single nail, screw, and paint shade to verify the work, you'd be writing that list for weeks. Instead, you take a high-resolution "before" photo. When the contractor says they're done, you don't check the nail list—you hold the photo up to the room. If everything matches the visual record, you're good. If a wall is suddenly three inches shorter, it jumps out at you immediately.

Snapshot testing is exactly that for your Scala data structures. Instead of writing twenty assertEquals statements for every single field in a deeply nested case class, you take a "photo" of the object—usually by serializing it to JSON or a string—and saving it to a file. The next time the test runs, Scala compares the current state of the object against that saved file. If they differ, the test fails and shows you the diff.

The Exhaustion of Manual Assertions

I've spent way too many hours of my career writing tests that look like this: assertEquals(result.user.profile.address.zipCode, "90210"). It's tedious, and frankly, it's brittle. When I add a new field to the Address case class, I have to go back and update fifty different tests just to acknowledge that the new field exists.

Let's look at a more realistic example. Suppose we're building a compiler's intermediate representation. We have a ProjectAnalysis structure that contains a map of modules, each with a list of dependencies and a set of metrics. Trying to assert this manually is a nightmare.

case class Metric(name: String, value: Double)
case class Module(name: String, dependencies: List[String], metrics: Set[Metric])
case class ProjectAnalysis(projectName: String, modules: Map[String, Module])

// Imagine this result is the product of a complex analysis algorithm
val actualAnalysis = analyzer.analyze(myProject)

If you write a standard test for this, you're essentially re-implementing the logic of the ProjectAnalysis class inside your test suite. That's a recipe for bugs.

Capturing the Gold Standard

With snapshot testing, you use a library (like scala-snapshot or a custom wrapper around a JSON library) to "freeze" the output. The first time you run the test, the framework sees there is no snapshot file, so it creates one—this is your "Gold Standard."

it should "produce the correct analysis for a standard project" in {
  val actualAnalysis = analyzer.analyze(myProject)
  
  // Instead of 10 different assertEquals, we do this:
  snapshot(actualAnalysis) 
}

The snapshot call serializes actualAnalysis into a file like ProjectAnalysis_test.snap. From that point forward, the test isn't checking if the data is "correct" in a vacuum—it's checking if the data has changed since you last verified it.

Handling the Drift

Now, here is where the mentor advice comes in: snapshot tests are incredibly powerful, but they can make you lazy. If you change your code and the snapshot fails, your first instinct will be to just "update the snapshot" to make the red light go green. Don't do that blindly.

When a snapshot fails, it's a signal. You need to look at the diff. If the diff shows that a module's dependency list changed from List("A", "B") to List("A"), you have to ask: "Did I intentionally remove a dependency, or did I just break the analyzer?"

I usually treat snapshot failures as a code review for my data. If the change is intentional, I explicitly commit the updated .snap file to version control. This turns your test snapshots into a living history of how your data structures have evolved over the life of the project.




📋 Practical Task

Implementing a Dependency Graph Snapshot Guard

You are working on a system that maps software dependencies. You have a DependencyGraph case class that is far too complex for standard assertions. Your task is to implement a mock snapshot verification flow.

Requirements:

  • Create a DependencyGraph case class that contains a projectName: String and a nodes: Map[String, List[String]] (where the key is the package and the value is a list of its dependencies).
  • Write a function verifySnapshot(current: DependencyGraph, snapshotFile: String).
  • Since you aren't using a real file system in this exercise, simulate the "snapshot file" using a hardcoded String that represents a previously saved JSON-like version of the graph.
  • The function should return a Boolean: true if the current graph's toString matches the snapshot string, and false if they differ.
  • Create a test case where you intentionally modify a dependency in the DependencyGraph and verify that verifySnapshot correctly detects the drift.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.