简体   繁体   中英

Nunit Assert.AreEqual() fails when comparing two custom objects

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);

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM