How to use Exclude in FluentAssertions for property in collection?

Liath picture Liath · Mar 3, 2014 · Viewed 28.2k times · Source

I have two classes:

public class ClassA
{
  public int? ID {get; set;}
  public IEnumerable<ClassB> Children {get; set;}
}

public class ClassB
{
  public int? ID {get; set;}
  public string Name {get; set;}
}

I want to use fluent assertions to compare to ClassA instances. However I want to ignore the IDs (because the IDs will have been assigned after the save).

I know I can do this:

expectedA.ShouldBeEquivalentTo(actualA, options => options.Excluding(x => x.PropertyPath == "Children[0].ID"));

Which I can obviously repeat for each ClassB in the collection. However I'm looking for a way to exclude the all the IDs (rather than doing an exclude for each element).

I've read this question however if I remove the [0] indexers the assertions fail.

Is this possible?

Answer

Dennis Doomen picture Dennis Doomen · Mar 4, 2014

What about?

expected.ShouldBeEquivalentTo(actualA, options => options.Excluding(su => 
   (su.RuntimeType == typeof(ClassB)) && (su.PropertyPath.EndsWith("Id")));`

Or you could do a RegEx match on the property path, such as

expected.ShouldBeEquivalentTo(actualA, options => options.Excluding(su => (Regex.IsMatch
   ("Children\[.+\]\.ID"));

I actually like that last one, but the regex stuff makes it a bit difficult to read. Maybe I should extend ISubjectInfo with a method to match the path against a wildcard pattern, so that you can do this:

expected.ShouldBeEquivalentTo(actualA, options => options
  .Excluding(su => su.PathMatches("Children[*].ID")));