1

Consider the function:

public static ulong[] productFib(ulong prod)
    {
        ulong fib1 = 0;
        ulong fib2 = 1;

        while ((fib1 * fib2) < prod)
        {
            ulong temp = fib1;
            fib1 = fib2;
            fib2 = temp + fib2;

        }

        return new ulong[] { fib1, fib2, 1 };
    }

I am working through a kata whose test looks like the following:

ulong[] r = new ulong[] { 55, 89, 1 };
Assert.AreEqual(r, Kata.productFib(4895));

In the immediate window, I can see that the return array is not only of type ulong but has the 3 elements I expect, yet MSTest fails with:

Message: Assert.AreEqual failed. Expected:<System.UInt64[]>. Actual:<System.UInt64[]>.

Is there something wrong with the test assertion, or my function, that would cause this test to fail?

Thank you

Elliot Rodriguez
  • 608
  • 6
  • 25
  • 2
    arrays are reference types, so you're not checking if they contain the same values, but if they are the exact same reference. Use `CollectionAssert.AreEqual` instead. – juharr Aug 31 '17 at 12:54
  • @juharr wish I could - the test is controlled by the application presenting the kata. Interestingly, I just discovered the same code passes the test presented by the kata. – Elliot Rodriguez Aug 31 '17 at 12:55
  • If you cannot use `CollecitonAssert` then just write a `for` loop and compare the values in the arrays to each other. – juharr Aug 31 '17 at 12:57
  • 1
    Another option would be to switch to `Tuple` since you only seem to deal with 3 values and since `Tuple` overrides `Equals` so `Assert.AreEqual` would do what you expect. – juharr Aug 31 '17 at 13:01
  • Thanks. What I find curious is the tests associated with the kata pass "as is", using the application's UI, and NUnit. – Elliot Rodriguez Aug 31 '17 at 13:59

2 Answers2

4

Assert.AreEqual() uses the Equals() method of the passed arguments. And arrays simply compare their references, not their content. So two different array instances will never pass this test.

You may use linq SequenceEqual like that:

Assert.IsTrue(r.SequenceEqual(Kata.productFib(4895)));
René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

C# arrays are reference types. Assert.AreEqual() will checking for reference equality rather than if you'd passed value types.

phuzi
  • 12,078
  • 3
  • 26
  • 50