views:

1024

answers:

3

I have two identical byte arrays in the following segment of code:

    /// <summary>
    ///A test for Bytes
    ///</summary>
    [TestMethod()]
    public void BytesTest() {
        byte[] bytes = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketData);
        TransferEventArgs target = new TransferEventArgs(bytes);

        byte[] expected = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketValue);
        byte[] actual;
        actual = target.Bytes;

        Assert.AreEqual(expected, actual);
    }

Both arrays are identical down to the very byte. In this scenario, why would Assert.AreEqual fail?

+7  A: 

Because arrays don't override Equals.

You haven't said which test framework you're using, but basically it would be up to that framework to special-case arrays. You can always implement your own helper method to do that, of course. I've done that sometimes. For a quick and dirty hack, if you're using .NET 3.5 you can use the Enumerable.SequenceEqual extension method:

Assert.IsTrue(actual.SequenceEqual(expected));

A custom helper method could give you more details about how they differ, of course. You might find the methods in MoreLINQ.TestExtensions helpful, although they're fairly rough and ready too.

Jon Skeet
I'm using VSTS unit tests. Is there a built-in alternate assertion I can use, or do a for-loop and compare the bytes, if they all equal out, then assert?
David Anderson
I'm afraid I haven't used VSTS unit tests - but tvanfosson's recommendation looks appropriate.
Jon Skeet
His answer worked out great, thanks Jon!
David Anderson
+11  A: 

Equals uses reference equality and, since they are different objects, they are not equal. You'll want to compare each byte in the array and verify that they are equal. One way to do this is convert them to something that implements ICollection and use CollectionAssert.AreEqual() instead.

tvanfosson
yup, that did the trick. thanks!
David Anderson
A: 

The method Assert.AreEqual under the hood will end up defaulting to Object.Equals() for non-null values. The default implementation of Object.Equals() is referential equality. The 2 arrays are identical value wise but difference reference wise and hence will not be considered equal.

JaredPar