Jevon Kendon
Jevon Kendon

Reputation: 686

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");

Upvotes: 3

Views: 131

Answers (2)

Dennis Doomen
Dennis Doomen

Reputation: 8909

Or switch to v5 so you compare your subject-under-test against an anonymous type where you only define the properties you care about for that particular test.

Upvotes: 2

Nkosi
Nkosi

Reputation: 247521

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");

Upvotes: 4

Related Questions