Snapshot testing

edit

Meziantou.Framework.SnapshotTesting and Meziantou.Framework.InlineSnapshotTesting write the value under test with the human-readable serializer. They create the options with their own defaults, such as the HTTP converters and the JSON and XML formatters, and let you change them:

  • In Meziantou.Framework.SnapshotTesting, ConfigureHumanReadableSerializer(options => ...) on the settings. See Serializers and comparers and Deterministic snapshots, which also covers the scrubbing methods such as ScrubGuid and UseRelativeDateTime.
  • In Meziantou.Framework.InlineSnapshotTesting, WithSerializer(options => ...) for one assertion, or UseHumanReadableSerializer(options => ...) on the settings. See Serializers.

The callback receives a HumanReadableSerializerOptions: everything on the other pages of this section applies.

Format HTML in every snapshot

Register the HTML formatter of Meziantou.Framework.HumanReadableSerializer.Html in a module initializer, so it applies to every test of the project. With Meziantou.Framework.SnapshotTesting:

using System.Runtime.CompilerServices;
using Meziantou.Framework.HumanReadable.ValueFormatters;
using Meziantou.Framework.SnapshotTesting;

namespace SnapshotTestingSample;

internal static class SnapshotConfiguration
{
    [ModuleInitializer]
    internal static void Initialize()
    {
        SnapshotSettings.Default.ConfigureHumanReadableSerializer(options => options.AddHtmlFormatter(new HtmlFormatterOptions
        {
            OrderAttributes = true,
        }));
    }
}

With Meziantou.Framework.InlineSnapshotTesting:

using System.Runtime.CompilerServices;
using Meziantou.Framework.HumanReadable.ValueFormatters;
using Meziantou.Framework.InlineSnapshotTesting;

namespace InlineSnapshotTestingSample;

internal static class SnapshotConfiguration
{
    [ModuleInitializer]
    internal static void Initialize()
    {
        var settings = InlineSnapshotSettings.Default with { };
        settings.UseHumanReadableSerializer(options => options.AddHtmlFormatter(new HtmlFormatterOptions
        {
            OrderAttributes = true,
        }));
        InlineSnapshotSettings.Default = settings;
    }
}

Keep snapshots stable