peter
peter

Reputation: 153

Equality of two objects in NUnit

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 ?

Upvotes: 2

Views: 1563

Answers (3)

Glaerferyn
Glaerferyn

Reputation: 211

Since the 4.1 version, NUnit is providing a UsingPropertiesComparer() suffix to the Is.EqualTo equality constraint. It will recursively check all the object public properties.

https://docs.nunit.org/articles/nunit/writing-tests/constraints/EqualConstraint.html#comparing-classesstructures

You will even get a specific message when a particular property fails the equality test !

Upvotes: 0

MohammadHossein
MohammadHossein

Reputation: 96

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

Upvotes: 0

Maxime
Maxime

Reputation: 2260

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.

Upvotes: 2

Related Questions