Bringing Jest-esque Snapshot testing to C#
Bringing Jest-esque Snapshot testing to C#
Snapper is a NuGet library which makes snapshot testing very easy in C#. Snapshot testing can simplify testing and is super useful when paired with Golden Master testing or contract testing APIs.
It is very heavily based on Jest Snapshot Testing framework.
See https://theramis.github.io/Snapper/ for the full documentation.
The best way to describe what Snapper does by going through an example.
Imagine you have the following test where are retrieving a user from a service.
[Fact]
public void MyTest()
{
var myUser = _userService.GetUser(id);
Assert.Equal("MyUser", myUser.Username);
Assert.Equal("email@example.com", myUser.Email);
Assert.Equal("myhash", myUser.PasswordHash);
...
...
}
As you can imagine the assertion steps in the test can get very long and hard to read.
Now lets see what the test would look like if Snapper is used.
[Fact]
public void MyTest()
{
var myUser = _userService.GetUser(id);
myUser.ShouldMatchSnapshot();
}
The test above is now asserting the myUser
object with a snapshot stored on disk. Snapper helps you create this snapshot at the beginnging (see Quick Start).
This is the basis of snapshot testing. The idea being a baseline is first generated (in this case a json file which is our snapshot) and then everytime the test runs the output is compared to the snapshot. If the snapshot and the output from the tests don’t match the test fails!
As you can see using Snapper the test is now much smaller and easier to read but that’s not all. Using Snapper brings with it a lot more benefits!
Benefits of using Snapper/snapshot testing vs traditional assertions
FirstName
to the myUser
object above. Using traditional assertions the test would still pass and it’s easy to forget to update the test. Using Snapper the test would immediately fail since it’s a change in the system and the developer should verify if the change was expected!Use cases where Snapper/snapshot testing really shines
The use cases above are just some of the examples I’ve found where Snapper is super useful. Feel free to try them in other situation you think would be useful.
Thanks goes to these wonderful people (emoji key):
Florian Gather 💻 🤔 | Tomas Bruckner 💻 | Michael Kriese 💻 🤔 🐛 | Taylor Kimmett 💻 | Patrick Lehner 🐛 | Piotr Litwinski 🐛 | Warren Ferrell 💻 |
Aaron Roberts 💻 🤔 | jaytulk 💻 | Alberto Martín 🐛 | Peter Huang 💻 | J Teeuwissen 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!