Home > Mobile >  Weird FluentAssertions behaviour with record classes
Weird FluentAssertions behaviour with record classes

Time:05-11

I have the following test that surprisingly passes:  

abstract record class Base(string Property1);
sealed record class SubClassA(string Property1) : Base(Property1);
sealed record class SubClassB(string Property1, string Property2) : Base(Property1);
    
[Fact]
public void Test()
{
    var a = new SubClassA("test");
    var b = new SubClassB("test", "test");
    b.Should().BeEquivalentTo(a);
}

In the FluentAssertions documentation it states that by default classes are compared using their members. How can this pass, since SubClassB clearly has one member more than SubClassA? I can make the test pass by changing to value semantics:

b.Should().BeEquivalentTo(a, options => options.ComparingRecordsByValue());

What is going on here? Thanks!

CodePudding user response:

Your assertion is telling FA to make sure that b is equivalent to a, and since SubClassA only has two properties, it will ignore the third property of SubClassB. In other words, the expectation drives the comparison.

  • Related