0

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 d 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(d);
    d.Should().BeEquivalentTo(a);

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

Lee Tickett
  • 5,847
  • 8
  • 31
  • 55

2 Answers2

0

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.

0

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!

  • Try it for yourself... You do need to check both. The first assertion will only check that all properties in `b` match those in `a`... but it doesn't care if `a` has a bunch of extra properties. The second assertion then handles that... – Lee Tickett Apr 20 '22 at 14:54
  • Not sure if you're right. If A and B are the same type MyObject than the IComparable.CompareTo() would return false if a.AnotherProp = 1 and b.AnotherProp = null. – Davi Bertolli Apr 20 '22 at 15:35
  • *has a bunch of extra properties* - how do two instances of the same class realize a situation where one of the instances has "more properties" than the other? In `var b = new MyObject { SomeProp = "hello" };` the `AnotherProp` doesn't cease to exist just because you didn't mention it; it just has a value that is `default` for its type – Caius Jard Apr 20 '22 at 16:39
  • You're quite right. I've confused myself. I was definitely having a problem where I think I had to do this... perhaps it was something to do with anonymous types. I'll take another look and try and clarify or post a new question. Thank you – Lee Tickett Apr 20 '22 at 19:24
  • OK I figured out what I was trying to do/why!!! It was comparing anonymous objects. I will have another search then if needed post a new question. – Lee Tickett Apr 26 '22 at 09:44