Member-only story
Comparing objects with disparate members in Fluent Assertions
One of the most powerful features of Fluent Assertions is its ability to do a deep comparison of two object graphs. There are tons of options to tell the library how to do that, but out of the box, it is smart enough to understand anonymous types, records and how to compare collections. But up to now, it did not know how to compare two objects with misnamed properties or fields. At least, not until version 6.5.
Imagine you want to assert that an OrderDto
is equivalent to an Order
entity using BeEquivalentTo. This is a pretty common thing to do in FA. But what if the first has an OrderName
property and the second a Name
property? Assuming that those two properties are supposed to contain the same value, you can now use the new WithMapping
option to tell FA that anytime it finds the Name
property on the expectation, it should compare it to the OrderName
property of the subject-under-test.
// Using names with the expectation member name first. Then the subject's member name.
orderDto.Should().BeEquivalentTo(order, options => options
.WithMapping("Name", "OrderName"));// Using expressions, but again, with expectation first, subject last.
orderDto.Should().BeEquivalentTo(order, options => options
.WithMapping<OrderDto>(e => e.Name, s => s.OrderName));
Another option is to map two deeply nested members to each other. In that case, your path must start at the root:
// Using dotted property paths…