How can you elegantly assert the following kind of equivalence between two .NET objects (ideally using the Fluent Assertions library)?
Two objects are structurally equivalent if:
- both objects are of the same (run-time) type, and
- the public properties of both objects are (recursively) structurally equivalent.
Note that subject.Should().BeEquivalentTo(expectation)
does not work since BeEquivalentTo
does not check type equality. For example, if we have two classes A
and B
each with a single property object X { get; set; }
, then the two objects
new A { X = new B { X = new A() }}
and
new B { X = new A { X = new B() }}
would be deemed equivalent by BeEquivalentTo
, even though their types and the types of their properties and subproperties do not match, and hence are not structurally equivalent by the above definition.