1

case I am working on is - what is best solution to compare two objects with properties but excluding members with null values.

Ex.

objectA.prop1 = "value1";
objectA.prop2 = "value2";
objectA.prop3 = "value3";

expectedObjectB.prop1 = null;
expectedObjectB.prop2 = "value2";
expectedObjectB.prop3 = null;

objectA.Should().BeEquivalentTo(expectedObjectB);

It compares all properties one-to-one. How to make it compare only prop2 in that case and ignore other? Should I use Exclude method?

MichalM
  • 11
  • 4

2 Answers2

0

One way to solve this is use an anonymous object. BeEquivalentTo looks at the expectation to decide what properties to consider when doing an structural equivalency comparison.

In this

class MyClass
{
    string Prop1 { get; set; }
    string Prop2 { get; set; }
}

var subject = new MyClass
{
    Prop1 = "IrrelevantValue",
    Prop2 = "value2"
}


var expected = new
{
    Prop2 = "value2"
}

objectA.Should().BeEquivalentTo(expected);

Jonas Nyrup
  • 2,376
  • 18
  • 25
0

Ok, I got it with custom IEquivalencyStep.

public class NullValueExcludingComparer : IEquivalencyStep
    {
        public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config)
        {
            return context.Expectation is null;
        }

        public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
        {
            return true;
        }
    }

And executing:

objectA.Should().BeEquivalentTo(expectedObjectB, options =>
    options.Using(new NullValueExcludingComparer())
);
MichalM
  • 11
  • 4