Kairan
Kairan

Reputation: 5542

Overriding equals method and unit testing

This is first attempt at unit testing. My .Equals method is failing on TestSet_Equals_True, TestSet_Equals_True_Shuffled_Order. Hoping for clarification as to whether this is a problem with HOW I Unit test or something is wrong with my .Equals method.

Unit Test:

private void Populate(Set set, int count)
{
    for (int i = 0; i < count; ++i)
        set.Add(i);
}

[TestMethod]
public void TestSet_Equals_True()
{
    Set set1 = new Set();
    Set set2 = new Set();

    Populate(set1, POPULATE_COUNT);
    Populate(set2, POPULATE_COUNT);
    bool expected = true;
    bool actual = set1.Equals(set2);
    Assert.AreEqual(expected, actual);
}

Class:

List<object> _set;

//Override Equals
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType())
    return false;
Set o = (Set)obj;

if (this._set.Count != o._set.Count)
    return false;

o._set.Sort();
this._set.Sort();

return _set.Equals(o._set); }

Upvotes: 0

Views: 3119

Answers (3)

manojlds
manojlds

Reputation: 301177

You can remove the Sort calls in your Equals. I don't know what purpose they serve and they should NOT be in an Equals implementation. List Equals just does reference equality. You can use the SequenceEquals extension method to IEnumerable<T> to check equality here:

var a = new List<int> {1, 2};
var b = new List<int> {1, 2};

Assert.False(a.Equals(b));
Assert.True(a.SequenceEqual(b));

Upvotes: 0

bas
bas

Reputation: 14912

First of all, don't sort your set inside an equal method. The Equals should not change your object in any way. It should only determine if 2 objects are identical.

You could use SequenceEquals but do realize that SequenceEquals does not handle NullReferenceExceptions.

So I think the problem is in your Equals implementation. Maybe you can try something like this:

    public override bool Equals(object obj)
    {
        var isEqual = false;

        var otherSet = obj as Set;

        if (otherSet != null)
        {
            isEqual = _set.Count == otherSet.Count;
            isEqual &= _set.SequenceEqual(otherSet);
        }

        return isEqual;
    }

Upvotes: 1

Shani Elharrar
Shani Elharrar

Reputation: 657

List<T> implementation of Equals is the default implementation of object.Equals - Reference Equality.

To see if two IEnumerable<T> are equal, You can use the extension method IEnumerable<T>.SequenceEquals - Don't forget to add using statement for System.Linq namespace.

Good luck.

Upvotes: 3

Related Questions