2

I'm working on a test for an interview and need to write a few classes that are then tested with Assert statements. There is one part where two objects are tested with Assert.AreEqual() immediately followed by a test with Assert.AreNotSame for the same two objects. My understanding is that the first test checks that two objects have the same values (a and b in my example) and the second test checks that they point two different objects in memory. However, the first Assert fails both in my example and in the program. Am I missing something about how those two Assert tests should work? How can they both pass?

public class Foo
{
    public int a { get; set; }
    public int b { get; set; }

    public Foo(int a, int b) { this.a = a; this.b = b; }
}
Foo a = new Foo();
a.a = 1;
a.b = 2;

Foo b = new Foo(1, 2);

Assert.AreEqual(a,b);//this fails
Assert.AreNotSame(a,b);
user8480182
  • 21
  • 1
  • 3
  • 3
    You need to implement an Equals override on Foo. Otherwise the default is reference equality. – Mike Zboray Nov 13 '18 at 07:27
  • @MikeZboray I'm just not sure if it's allowed but I can't think how else to make it pass. – user8480182 Nov 13 '18 at 07:29
  • What is the point of this test? Is it not to modify the code of Foo to make the test pass? You are the one with the test so you'll have provide more of the context for us. – Mike Zboray Nov 13 '18 at 07:36
  • @MikeZboray The instructions are very ambiguous (on purpose I believe) but the design of the classes is up to me - there's no templates provided. – user8480182 Nov 13 '18 at 07:38
  • this is the test https://www.alliancereservations.com/developer-test.html – user8480182 Nov 13 '18 at 07:39

1 Answers1

3

Both objects are not equal and not same since it is two different instances of the object.

If you override Equals method on the object than you can implement it in a way that you check if the properties of both objects are equal. If they are than the object is also equal. So your new class should look like this...

public class Foo
{
    public int a { get; set; }
    public int b { get; set; }

    public Foo(int a, int b) { this.a = a; this.b = b; }

    public override bool Equals(object obj)
    {
        return ((Foo)obj).a == this.a && ((Foo)obj).b == this.b;
    }
}

Also check this SO answer for further clarification...

Robert
  • 2,407
  • 1
  • 24
  • 35
  • This implementation can throw invalid cast and null reference exceptions. Exceptions are not expected from Equals/GetHashCode methods. – György Kőszeg Nov 13 '18 at 08:39
  • @taffer You missed the point in order to make your own point. Of course it can throw those two exception. This was just a show case of why his code is working the way it is working. – Robert Nov 13 '18 at 08:47