19

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.

3
  • can you post your error ? Commented Jun 28, 2014 at 7:00
  • Since there is already a good answer, I would like to suggest grabbing FluentAssertions as it has a ton of really nice methods for working with IEnumerable objects and other objects in general. Commented Jun 28, 2014 at 7:06
  • The anwer of @Anri was correct, the test passed. Commented Jun 28, 2014 at 7:26

1 Answer 1

45

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?

Sign up to request clarification or add additional context in comments.

3 Comments

I have no idea, I just have to write the tests. But tell me what's your idea.
Well, I would need to see the whole class, but from what is pasted here - you should create private int[] _position; in that class and use it in your getter and setter instead of creating new array every time.
if you pass a private array reference to a caller as result of a property getter, they can keep the reference to it and change values in it / cause hard to find bugs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.