Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two arrays in unit test throwing a AssertFailedException

I'm writing an unit tests for ready code and I'm receiving an unexpected AssertFailedException trying to run one of the test. Here is he:

[TestMethod]
    public void TestPositionGetter()
    {
        testPlayer.Position = new int[] { 1, 3 };
        int[] expectedPosition = testPlayer.Position;
        Assert.AreEqual(expectedPosition, testPlayer.Position);
    }

And here is the Position property in the Player class that I'm trying to test:

public int[] Position
    {
        get
        {
            return new int[] { this.PositionX, this.PositionY };
        }
        set
        {
            this.PositionX = value[0];
            this.PositionY = value[1];
        }
    }

Debugging the test, in local variables window player.Position and expectedPosition are looking similar but the test is still failing. I'm afraid the problem is coming from references.

like image 249
Stanimir Yakimov Avatar asked Jun 28 '14 06:06

Stanimir Yakimov


1 Answers

You are comparing different instances of an int[]. Assert.AreEqual compares by reference. Try CollectionAssert.AreEqual.

CollectionAssert.AreEqual(expectedPosition, testPlayer.Position);

This will compare array elements.

Also, your Position property smells like bad design. Do you really have to create new array every time you get a value?

like image 100
Anri Avatar answered Nov 11 '22 20:11

Anri