簡體   English   中英

使用 BeEquivalentTo 時,我可以告訴 FluentAssertions 忽略 Equals 方法嗎

[英]Can I tell FluentAssertions to ignore Equals method when using BeEquivalentTo

我有一個簡單的類,它有兩個屬性並覆蓋了 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);
}

您只需要在 EquivalencyAssertionOptions 中為您的類型覆蓋相等比較器,如下所示:

p1.Should().BeEquivalentTo(p2, options => options.ComparingByMembers<Person>())

您還可以使用動態對象。

[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
        }
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM