我有一个具有两个属性的简单类,并且Equals方法被覆盖了:
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);
}
}
现在,我创建了一个简单的测试,其中Id
的值相同,但是Name
的值不同。
[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
}
我从文档中了解到BeEquivalentTo()
在类中被重写时默认使用Equals()
方法,但是我还没有找到一种否决该方法的方法,因此实例被它们的实例进行比较属性值。
是否可以通过以下方法在FluentAssertions中执行此操作?
[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);
}
答案 0 :(得分:3)
您只需要在EquivalencyAssertionOptions中为您的类型重写相等比较器:
p1.Should().BeEquivalentTo(p2, options => options.ComparingByMembers<Person>())
答案 1 :(得分:0)
您也可以使用动态对象。
[Fact]
public void PersonShouldNotBeEqual()
{
var guid = Guid.NewGuid();
var p1 = new Person { Id = guid, Name = "Me" };
dynamic p2 = new { Id = guid, Name = "You" };
p1.Should().NotBeEquivalentTo(p2);
dynamic p3 = new { Id = guid, Name = "Me" };
p1.Should().BeEquivalentTo(p3);
}
如果您还需要嵌套对象比较,也可以对它们使用动态。
dynamic expected = new
{
Id = 123,
Name = "John Doe",
City = new {
Id = 456,
Name = "Paris"
Country = new {
Id = 789,
Name = France
}
}
};