Search code examples
c#unit-testingfluent-assertions

FluentAssertions factor out repeated config


I have unit-test code like this:

// version3 should be a copy of version2 with some differences
version3.Data.ShouldBeEquivalentTo(version2,
  option => option
    .Excluding(x => x.Id)
    .Excluding(x => x.Status)
    .Excluding(x => x.Stale)
    .Excluding(x => x.Body)
    .Excluding(x => x.CreatedBy)
    .Excluding(x => x.UpdatedBy),
  "because version3 is version2 updated");

And then again

// version4 should be a copy of version3 with some differences
version4.Data.ShouldBeEquivalentTo(version3,
  option => option
    .Excluding(x => x.Id)
    .Excluding(x => x.Status)
    .Excluding(x => x.Stale)
    .Excluding(x => x.Body)
    .Excluding(x => x.CreatedBy)
    .Excluding(x => x.UpdatedBy),
  "because version4 is version3 updated");

How can I factor option out?

I would like to make something like this:

// version3 should be a copy of version2 with some differences
version3.Data.ShouldBeEquivalentTo(version2,
  option => baseOption,
  "because version3 is version2 updated");

And maybe even this:

// version3 should be a copy of version2 with some differences
version3.Data.ShouldBeEquivalentTo(version2,
  option => baseOption
    .Excluding(x => x.OtherProperty),
  "because version3 is version2 updated");

Solution

  • Declare the option delegate externally as the base

    Func<FluentAssertions.Equivalency.EquivalencyAssertionOptions<MyDataType>,
        FluentAssertions.Equivalency.EquivalencyAssertionOptions<MyDataType>>
        baseOption = option => option
            .Excluding(x => x.Id)
            .Excluding(x => x.Status);
    

    And use it with the assertion

    // version3 should be a copy of version2 with some differences
    version3.Data.ShouldBeEquivalentTo(version2, baseOption, 
        "because version3 is version2 updated");
    

    For other assertion that needs to build upon the base you have to invoke the delegate and append additional options

    // version3 should be a copy of version2 with some differences
    version3.Data.ShouldBeEquivalentTo(version2,
      option => baseOption(option)
        .Excluding(x => x.OtherProperty),
      "because version3 is version2 updated");
    

    You should note that the current syntax being used has been deprecated in newer versions of the framework.

    version3.Should().BeEquivalentTo(version2, baseOption, 
        "because version3 is version2 updated");