Question

I have written my custom generic linked list and wanted to test various methods. For example I have Contains method

    public bool Contains(T item)
    {
        lock (this)
        {
            Node<T> currentNode = firstNode;
            while (currentNode != null)
            {
                if (currentNode.Item != null)
                {
                    if (currentNode.Item.Equals(item))
                    {
                        return true;
                    }
                }
                currentNode = currentNode.Next;
            }
            return false;
        }
    }

I used MSTest to generate a unit test for this, which generates this stub. I am not sure what should I put at TODO lines??

    public void AddTestHelper<T>()
    {
        LinkedList<T> target = new LinkedList<T>(); // TODO: Initialize to an appropriate value
        T item = default(T); // TODO: Initialize to an appropriate value
        target.Add(item);
        Assert.AreEqual(target.Contains(item), true);
    }

    [TestMethod()]
    public void AddTest()
    {
        AddTestHelper<int>(); // my lines
        AddTestHelper<object>(); //my lines
    }

However AddTestHelper or AddTestHelper fails as the default(T) gives null for which Contains() method returns false and test fails.

I am new to unit test, and not sure how to test generic method like this. Can someone tell me what change is requires in the Test method specially in TODO lines??

Thanks

Was it helpful?

Solution

Change the method to take the generic type instance value as shown below

public void AddTestHelper<T>(T item)
   {
    LinkedList<T> target = new LinkedList<T>();      
    target.Add(item);
    Assert.AreEqual(target.Contains(item), true);
  }

so use instance in the code instead

so in your tests u can do

 AddTestHelper<int>(12);    

 AddTestHelper<string>("Test");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top