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?
CodePudding user response:
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);
}
}
CodePudding user response:
The Fluent Assertion's specification says that all public members of the expected object must be available on the test object otherwise an exception will be thrown:
testObject.Should().BeEquivalentTo(expectedObject);
If you substitute
- expectedObject -> test
- testObject -> testDto
testDto.Should().BeEquivalentTo(test);
then it will work as you expected, it will throw the exception.
But if you replace the two object as you did, it will not throw the exception, since in that case all the props of the expected (testDto) are existing in the testObject (test).