Snapshot testing
editMeziantou.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 asScrubGuidandUseRelativeDateTime. - In
Meziantou.Framework.InlineSnapshotTesting,WithSerializer(options => ...)for one assertion, orUseHumanReadableSerializer(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
- Sort the members and dictionary keys with
StringComparer.Ordinal(Members). - Skip the members that change on every run, such as ids and timestamps, with IgnoreMember, or write them with a converter (Members, Converters).
- Exclude or rewrite the HTTP headers that change (HTTP messages).
- Turn on ShowInvisibleCharactersInValues when two snapshots differ only by whitespace (Output format).