304NotModified / Verify

Verify is a snapshot tool that simplifies the assertion of complex data models and documents.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Verify

Discussions Build status NuGet Status NuGet Status NuGet Status NuGet Status

Verify is a snapshot tool that simplifies the assertion of complex data models and documents.

Verify is called on the test result during the assertion phase. It serializes that result and stores it in a file that matches the test name. On the next test execution, the result is again serialized and compared to the existing file. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new result.


Part of the .NET Foundation

NuGet packages

Snapshot management

Accepting or declining a snapshot file is part of the core workflow of Verify. There are several ways to do this and the approach(s) selected is a personal preference.

Usage

All examples use ImplicitUsings. Ensure the following is set to have examples compile correctly <ImplicitUsings>enable</ImplicitUsings>

Class being tested

Given a class to be tested:

public static class ClassBeingTested
{
    public static Person FindPerson()
    {
        return new()
        {
            Id = new("ebced679-45d3-4653-8791-3d969c4a986c"),
            Title = Title.Mr,
            GivenNames = "John",
            FamilyName = "Smith",
            Spouse = "Jill",
            Children = new()
            {
                "Sam",
                "Mary"
            },
            Address = new()
            {
                Street = "4 Puddle Lane",
                Country = "USA"
            }
        };
    }
}

snippet source | anchor

xUnit

Support for xUnit

[UsesVerify]
public class Sample
{
    [Fact]
    public Task Test()
    {
        var person = ClassBeingTested.FindPerson();
        return Verify(person);
    }
}

snippet source | anchor

NUnit

Support for NUnit

[TestFixture]
public class Sample
{
    [Test]
    public Task Test()
    {
        var person = ClassBeingTested.FindPerson();
        return Verify(person);
    }
}

snippet source | anchor

Expecto

Support for Expecto

open Expecto
open VerifyTests
open VerifyExpecto

[<Tests>]
let tests =
  testTask "findPerson" {
    let person = ClassBeingTested.FindPerson();
    do! Verifier.Verify("findPerson", person)
  }

snippet source | anchor

Caveats

Due to the nature of the Expecto implementation, the following APIs in Verify are not supported.

  • settings.UseTypeName()
  • settings.UseMethodName()
  • settings.UseParameters()
  • settings.UseTextForParameters()

Instead use a custom name parameter.

MSTest

Support for MSTest

[TestClass]
public class Sample :
    VerifyBase
{
    [TestMethod]
    public Task Test()
    {
        var person = ClassBeingTested.FindPerson();
        return Verify(person);
    }
}

snippet source | anchor

Initial Verification

When the test is initially run will fail with:

First verification. Sample.Test.verified.txt not found.
Verification command has been copied to the clipboard.

The clipboard will contain the following:

cmd /c move /Y "C:\Code\Sample\Sample.Test.received.txt" "C:\Code\Sample\Sample.Test.verified.txt"

Notes:

If a Diff Tool is detected it will display the diff:

InitialDiff

To verify the result:

  • Execute the command from the clipboard, or
  • Use the diff tool to accept the changes, or
  • Manually copy the text to the new file

Verified result

This will result in the Sample.Test.verified.txt being created:

{
  GivenNames: John,
  FamilyName: Smith,
  Spouse: Jill,
  Address: {
    Street: 4 Puddle Lane,
    Country: USA
  },
  Children: [
    Sam,
    Mary
  ],
  Id: Guid_1
}

snippet source | anchor

Subsequent Verification

If the implementation of ClassBeingTested changes:

public static class ClassBeingTested
{
    public static Person FindPerson()
    {
        return new()
        {
            Id = new("ebced679-45d3-4653-8791-3d969c4a986c"),
            Title = Title.Mr,
            // Middle name added
            GivenNames = "John James",
            FamilyName = "Smith",
            Spouse = "Jill",
            Children = new()
            {
                "Sam",
                "Mary"
            },
            Address = new()
            {
                // Address changed
                Street = "64 Barnett Street",
                Country = "USA"
            }
        };
    }
}

snippet source | anchor

And the test is re run it will fail with

Verification command has been copied to the clipboard.
Assert.Equal() Failure
                                  ↓ (pos 21)
Expected: ···\n  GivenNames: 'John',\n  FamilyName: 'Smith',\n  Spouse: 'Jill···
Actual:   ···\n  GivenNames: 'John James',\n  FamilyName: 'Smith',\n  Spouse:···
                                  ↑ (pos 21)

The clipboard will again contain the following:

cmd /c move /Y "C:\Code\Sample\Sample.Test.received.txt" "C:\Code\Sample\Sample.Test.verified.txt"

See also: Clipboard

The Diff Tool will display the diff:

SecondDiff

The same approach can be used to verify the results and the change to Sample.Test.verified.txt is committed to source control along with the change to ClassBeingTested.

VerifyJson

VerifyJson performs the following actions

  • Convert to JToken (if necessary).
  • Apply ignore member by name for keys.
  • PrettyPrint the resulting text.

[Fact]
public Task VerifyJsonString()
{
    var json = "{'key': {'msg': 'No action taken'}}";
    return VerifyJson(json);
}

[Fact]
public Task VerifyJsonStream()
{
    var json = "{'key': {'msg': 'No action taken'}}";
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
    return VerifyJson(stream);
}

[Fact]
public Task VerifyJsonJToken()
{
    var json = "{'key': {'msg': 'No action taken'}}";
    var target = JToken.Parse(json);
    return VerifyJson(target);
}

snippet source | anchor

Results in:

{
  key: {
    msg: No action taken
  }
}

snippet source | anchor

Received and Verified

  • All *.verified.* files should be committed to source control.
  • All *.received.* files should be excluded from source control.

Static settings

Most settings are available at the both global level and at the instance level.

When modifying settings at the both global level it should be done using a Module Initializer:

[UsesVerify]
public class StaticSettings
{
    [Fact]
    public Task Test()
    {
        return Verify("String to verify");
    }
}

public static class StaticSettingsUsage
{
    [ModuleInitializer]
    public static void Initialize()
    {
        VerifierSettings.AddScrubber(_ => _.Replace("String to verify", "new value"));
    }
}

snippet source | anchor

Versioning

Verify follows Semantic Versioning. The same applies for extensions to Verify. Small changes in the resulting snapshot files may be deployed in a minor version. As such nuget updates to Verify.* should be done as follows:

  • Updates all Verify.*packages in isolation
  • Re-run all tests.
  • If there are changes, ensure they look correct given the release notes. If the changes do not look correct, raise an issue.
  • Accept those changes.

Snapshot changes do not trigger a major version change to avoid causing Diamond dependency issues for downstream extensions.

Media

Extensions

More Documentation

Alternatives

Projects/tools that may be a better alternative to Verify

Icon

Helmet designed by Leonidas Ikonomou from The Noun Project.

About

Verify is a snapshot tool that simplifies the assertion of complex data models and documents.

License:MIT License


Languages

Language:C# 99.7%Language:F# 0.3%Language:HTML 0.0%