Question

In FluentAssertions I can use the AllProperties.But(obj => obj.property_I_do_not_want) to remove specific properties from a comparison assertion which is fine when I know the names of the properties I want to ignore but in my situation I only want to ignore unitialized properties. For now I would be willing to just ignore one's equal to null but if there's a solution that also excludes primitives set to their default values that would be extra handy.

I started out be trying to write an extension method for the PropertyAssertions class but can't figure out how to create an IEnumerable<Expression<T>> that includes an Expression<T> for accessing each property to ignore to pass to the But method.

Was it helpful?

Solution

If you're willing to try the 2.0 beta, you can use a lambda in the new ShouldBeEquivalentTo() API to exclude certain properties like this:

subject.ShouldBeEquivalentTo(expected, options =>
    options.Excluding(ctx => ctx.PropertyPath == "Level.Level.Text"));

If you want, you can even encapsulate this in a custom rule (a class implementing ISelectionRule) like this:

subject.ShouldBeEquivalentTo(expected, options => 
    options.Using(new ExcludeUninitializedProperties()));

In fact, you could even make this the default for particular types by overriding the factory method that creates the initial options:

EquivalencyAssertionOptions<TSubject>>.Default = () =>    
    EquivalencyAssertionOptions<TSubject>>.Default.Using(new ExcludeUninitializedProperties())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top