Home > Mobile >  Assert object equivalence by value
Assert object equivalence by value

Time:04-20

I'm sure i'm missing the obvious...

Say we have:

public class MyObject
{
    public string SomeProp { get; set; }
    public int AnotherProp { get; set; }
}

[Fact]
public void SomeTest()
{
    var a = new MyObject { SomeProp = "hello", AnotherProp = 9 };
    var b = new MyObject { SomeProp = "hello" };
    var c = new MyObject { AnotherProp = 9 };
    var d = new MyObject { SomeProp = "hello", AnotherProp = 9 };
}

What is the correct assertion to check that all of the properties match (e.g. a and b would return true, but all other combinations would return false?

At the moment, i'm doing equivalency checks, but have to do it in both directions? e.g.

    a.Should().BeEquivalentTo(b);
    b.Should().BeEquivalentTo(a);

Forgive me if this is clearly defined in the docs... I can't find it :/

CodePudding user response:

You can do something like

public class MyObject
{
    public string SomeProp { get; set; }
    public int AnotherProp { get; set; }

    public override bool Equals(object obj)
    {
        var other = obj as MyObject;

        if (other == null)
            return false;

        return other.SomeProp == SomeProp &&
               other.AnotherProp == AnotherProp;
    }
}

and then just do

Assert.True(a.Equals(d));

I do not know if there is any other way of doing this.

CodePudding user response:

Check the fluent assertions documentation here. It recommends implementing IComparable interface for what you need.

Also, if you check this:

a.Should().BeEquivalentTo(b);

You wouldnt/shouldnt check the oposite direction:

    b.Should().BeEquivalentTo(a);

Cause thats the same!

  • Related