Why does Assert.AreEqual(T obj1, Tobj2) fail with identical byte arrays

David Anderson picture David Anderson · Sep 3, 2009 · Viewed 29.5k times · Source

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?

Answer

tvanfosson picture tvanfosson · Sep 3, 2009

Assert.Equals tests using the Equals method, which by default 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.