Search code examples
c#unit-testingxunitfluent-assertions

Unexpected behaviour using BeEquivalentTo in Fluent Assertions


I'm having an issue with fluent assertions that seems to go against what the documentation is stating. I have this simple case to show the problem.

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        var test = new Test { Name = "Test", Value = "123" };
        var testDto = new TestDto { Name = "Test" };

        test.Should().BeEquivalentTo(testDto);
    }
}

public class Test
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class TestDto
{
    public string Name { get; set; }
} 

I would expect that this test would fail based on the fact that the "Value" property doesn't exist on the TestDto class.

The documentation states that my understanding would be correct based on this sentence.

All public members of the Order object must be available on the OrderDto having the same name. If any members are missing, an exception will be thrown.

Am I understanding this incorrectly or is this an issue within Fluent Assertions?


Solution

  • This is expected behavior. Fluent Assertion evaluate the object graph by matching exposed properties of TestDto on Test.

    Try to invert the order and the assertion fail as expected.

    public class UnitTest1
    {
        [Fact]
        public void DoesNotFail()
        {
            var test = new Test { Name = "Test", Value = "123" };
            var testDto = new TestDto { Name = "Test" };
    
            test.Should().BeEquivalentTo(testDto);
        }
    
        [Fact]
        public void WillFail()
        {
            var test = new Test { Name = "Test", Value = "123" };
            var testDto = new TestDto { Name = "Test" };
    
            testDto.Should().BeEquivalentTo(test);
        }
    }