Snapshot Testing with JUnit5

- 1 min

“Snapshot testing” is a technique to conveniently assert on the contents and structure of more complex data objects. The principle is simple: During first execution of a test, you take a “snapshot” of the actual result object produced by the code under test. This result is stored on disk and also checked into the SCM. In every subsequent test execution, the now actual result will be compared to the persisted snapshot.

If the comparison fails, the framework can provide you with a detailed diff of all the places where it found mismatches between the persisted snapshot and the actual test result. If you consider a large object with n attributes, you basically get n assertions for only writing a single one.

To provide the highest value

  1. it must be simple to write a snapshot assertion
  2. it must be simple to update multiple snapshot files in case the requirements change
  3. an assertion failure must be displayed in an appealing and meaningful way, so that mismatches can easily be identified by the human eye

When writing a test or an assertion you do not want to bother about: how to serialize test results, where and how to store the snapshot file and how to compare complex objects or how to properly display mismatches. You also do not want to manually update possibly houndreds of snapshots when the requirements change.

That is why I’ve implemented all these use-cases as a JUnit5 extension in this handy little library.

The code can be found on GitHub and the library of course is available from MavenCentral

rss facebook twitter github gitlab dev youtube mail spotify lastfm instagram linkedin xing google google-plus pinterest medium vimeo stackoverflow reddit quora quora