Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test failure in C# Prime Factors Kata

Longtime programmer, new to C#. Just started on the Prime Factors Kata using VS2012 and the built-in test framework. On the first test, the expected and actual match, yet it's flagged as a failure. Can anyone explain why, and more importantly what the work-around is?

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PrimeFactorsKata
{
    [TestClass]
    public class UnitTest1
    {
        private static List<int> ExpectedList()
        {
            return new List<int>();
        }

        [TestMethod]
        public void TestOne()
        {
            Assert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));
        }
    }

    class PrimeFactorGenerator
    {
        public static List<int> Generate(int n)
        {
            return new List<int>();
        }
    }
}

Output:

Assert.AreEqual failed. 
Expected:<System.Collections.Generic.List`1[System.Int32]>. 
Actual:<System.Collections.Generic.List`1[System.Int32]>. 

   at PrimeFactorsTest.UnitTest1.TestOne() in UnitTest1.cs: line 17
like image 446
pates Avatar asked Feb 11 '23 03:02

pates


2 Answers

As other's have mentioned you are comparing the references of each list, which are different. To compare the contents you can use CollectionAssert.AreEqual

[TestMethod]
public void TestOne()
{
    CollectionAssert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));
}

You can also check out other methods on CollectionAssert like AreEquivalent

There are also overrides for each that allow you to pass an IComparer to determine how you want to compare the items in the collections.

like image 189
juharr Avatar answered Feb 13 '23 21:02

juharr


You are trying to compare two different object references.

Assert.AreEqual(ExpectedList(), PrimeFactorGenerator.Generate(1));

This is calling ExpectedList() then it is calling PrimeFactorGenerator.Generate(1). Each one of the calls is creating and returning a reference to a new object (because of the new keyword you have). The Assert.AreEqual() is then comparing the references which obviously are not the same.

It is important to understand the difference between the reference and the object content. The reference is a pointer to the object value (content).

What you need to do is to loop through the two lists and compare the content (assuming that you inserted some data in them, in your sample they are empty but this code will still work):

var l1 = ExpectedList();
var l2 = PrimeFactorGenerator.Generate(1);

Assert.AreEqual(l1.Count, l2.Count);

if (l1.Count > 0) //Make sure you have data
    for (int i = 0, i < l1.Count, i++)
        Assert.AreEqual(l1[i], l2[i]);
like image 29
Moslem Ben Dhaou Avatar answered Feb 13 '23 19:02

Moslem Ben Dhaou