1

I am currently trying to test that two C# objects are the same (not referencing the same object, but have the same values). Trying to use Assert.Equals gives me "Assert.Equals should not be used for Assertions". What should I use ?

peter
  • 143
  • 2
  • 4
  • 10
  • Possible duplicate of [NUnit's Assert.Equals throws exception "Assert.Equals should not be used for assertions"](https://stackoverflow.com/questions/11584429/nunits-assert-equals-throws-exception-assert-equals-should-not-be-used-for-ass) – YuvShap Jul 14 '17 at 12:23

2 Answers2

2

Use Asset.AreEqual.

The Asset class is a child of the object class (like any class in C#) and when you call Asset.Equals you are actually calling the method object.Equals which is not what you want to do.

Programmers of NUnit probably put an exception in Asset.Equals to prevent people from making the mistake of using the wrong equality method.

Maxime
  • 2,192
  • 1
  • 18
  • 23
  • Assert.AreEquals does not exist. I used Assert.AreEqual() and getting Additional information: Expected: a But Was: b... where a and b are the same classes :). – peter Jul 14 '17 at 12:38
  • To make two classes comparable between each other you need to override the object.Equals method in the class you want to compare. Assert.AreEqual is using the Equals method of the objects to compare because it cannot know on what field/properties you want to compare the objects. Here is a link that might help you: https://msdn.microsoft.com/ru-ru/library/ms173147(v=vs.80).aspx – Maxime Jul 14 '17 at 12:47
0

for this, you should override Equals Method in Your Class

public class Student
{
    public int Age { get; set; }
    public double Grade { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }
        if (!(obj is Student))
        {
            return false;
        }
        Student st = obj as Student;
        return (st.Age == this.Age &&
            st.Grade == this.Grade);
    }

}

then you can write this Code in Your Test Class:

Assert.AreEqual(st1,st2);
MohammadHossein
  • 51
  • 1
  • 3
  • 12