Library: Verify - Snapshot Testing

Library: Verify - Snapshot Testing

Simplify Complex Object Testing

Published on Thursday, January 2, 2025

Verify

Verify is an open-source C# snapshot testing tool that helps us verify that complex objects are correct.

Snapshot Testing

Snapshot testing captures the output of the component, function, and UI and compares it to a previously stored snapshot. It is commonly used for the front end, but it is even more helpful for the back end when we have a code that is often changed or is in active development.

For example, if I'm working on, let's say, a GetPerson functionality, and I'm planning to add additional properties for the returning person object, the traditional way would be to:

var person = _getPersonHandler.Handle(id);
person.Name.Should().Be(Vuk);
person.YearOfBirth.Should().Be(1983);

This approach works exceptionally well. Tests are easy to write; you can even use LLMs like ChatGPT to write tests quickly. However, the problem begins when you have a lot of tests like this, and you want to add additional properties to a result. In the traditional approach, you would have to go through every test and test the property Surname, for example.

With Snapshot testing, you can test the values of all properties in the object. With modern IDEs, you only need to confirm (or reject) the new proposed value. The next time the test is run, it will compare the new value to the stored one.

The only problem with this approach is that you do not see the expected values inside the tests. You must manually find the stored expected value (usually in JSON format).

var person = _getPersonHandler.Handle(id);
await Verify(person);

In this simple example, if you add a property to a person, such as a surname, the test will fail, showing that the currently expected result does not include this additional property.

Conclusion

Snapshot testing with Verify is a fantastic tool that solves the problem of asserting large objects with many properties. Tools like GitHub Copilot can help us write assertions quicker, but they cannot automatically add new properties in 'ever-changing' classes for assertion. For use cases with many properties or features often changed, snapshot testing is an excellent alternative to traditional assertions.

However, it is essential to understand that snapshot testing is not a silver bullet. If we aim to test a fixed set of object values, traditional assertions are still the best option because they are more readable and easier to understand.