I have a simple class with two properties and the Equals method overridden:
public class Person : IEquatable<Person>
{
public Guid Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
return this.Equals(obj as Person);
}
public bool Equals(Person other)
{
return other != null &&
this.Id.Equals(other.Id);
}
public override int GetHashCode()
{
return 2108858624 + EqualityComparer<Guid>.Default.GetHashCode(this.Id);
}
}
Now I created a simple test, where the Id
values are the same, but the Name
values are different.
[Fact]
public void PersonShouldNotBeEqual()
{
var guid = Guid.NewGuid();
var p1 = new Person { Id = guid, Name = "Me" };
var p2 = new Person { Id = guid, Name = "You" };
p1.Should().NotBeEquivalentTo(p2); // Fails
}
I understood from the documentation that BeEquivalentTo()
uses the Equals()
method by default when it is overridden in the class, but I haven't found a way to overrule that so the instances are compared by their property values.
Is it possible to do this in FluentAssertions other then the way below?
[Fact]
public void PersonShouldBeEqual()
{
var guid = Guid.NewGuid();
var p1 = new Person { Id = guid, Name = "Me" };
var p2 = new Person { Id = guid, Name = "You" };
p1.Id.Should().Be(p2.Id);
p1.Name.Should().Be(p2.Name);
}
Person
had aCompany
property and we'd want to force member-wise comparison there too? Can this setting be applied somehow on a global level so that the entire object graph gets affected? – Darcee