Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Unit Testing Assert.AreEqual Fails with Identical Expected and Actual Values

I am a total newb when it comes to Unit Testing, so please pardon me if this is total ignorance. But I can't get this method to pass a unit test even if I provide the exact same values for the expected and actual. When I set breakpoints and step through, I have confirmed that both expected and actual variables are a string array containing two items, blah and blah. But the test still fails every time stating that "Assert.AreEqual failed. Expected: System.String[] Actual:System.String[]"

namespace TestProject1

{
 public class Testing
 {
    public string[] PMDate(string lastPm)
    {
        if (string.IsNullOrEmpty(lastPm))
            return new []{"blah", "blah"};
        string[] results = lastPm.Split(new[] {" "}, StringSplitOptions.None);

        if (results.Length < 2)
            return new[] {"blah", "blah"};

        return results;
    }
 }
[TestClass()]
public class UnitTest1
{
    [TestMethod()]
    public void PmDateTest()
    {
        Testing test = new Testing();
        string[] expected = test.PMDate("01/01/1900");
        string[] actual = test.PMDate("01/01/1900");
        Assert.AreEqual(expected, actual);
    }
}

}

like image 391
jmease Avatar asked Aug 21 '12 19:08

jmease


1 Answers

Your test will be using object.Equals, which isn't overridden for arrays. In other words, this will print false:

var x = new[] { 0 };
var y = new[] { 0 };
Console.WriteLine(x.Equals(y));

You should use CollectionAssert instead for collections:

CollectionAssert.AreEqual(expected, actual);
like image 71
Jon Skeet Avatar answered Nov 11 '22 19:11

Jon Skeet