views:

77

answers:

1

Consider this programs

public class ItemManager
{
    private ItemFetcher itemFetcher;
    public ItemManager(ItemFetcher _itemFetcher)
    {
        itemFetcher = _itemFetcher;
    }
    public List<Item> GetItemsFomTable()
    {
        List<Item> itemsList = new List<Item>();
        Item item;

        DataTable resultDataTable = itemFetcher.GetItemsFromDB();

        foreach (DataRow row in resultDataTable.Rows)
        {
            item = new Item();
            // set item's name property
            // set item's price property
            itemsList.Add(item);
        }
        return itemsList; 
    }
}
public class Item
{
    string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    double price;

    public double Price
    {
        get { return price; }
        set { price = value; }
    }
}
public class ItemFetcher
{
    public virtual DataTable GetItemsFromDB()
    {
        // DoSomething and fetch records in DataTable and return
        return new DataTable();
    }
}

I want to test itemFetcher.GetItemsFromDB method is called once in the method "GetItemsFomTable()" of the class ItemManager. Here is the Test

[TestFixture]
    public class ItemManagerTester
    {        
        [SetUp]
        public void Init()
        {

        }
        [Test]
        public void TestForGetItemsFomTable()
        {
            var mockItemFetcher = new Mock<ItemFetcher>();
            var itemManager = new ItemManager(mockItemFetcher.Object);

            mockItemFetcher.Setup(x => x.GetItemsFromDB());
            itemManager.GetItemsFomTable();

            mockItemFetcher.VerifyAll();
        }
    }

As you may see there is List initialised inside the method under test

List<Item> itemsList = new List<Item>();

I get this Exception raised:

TestCase 'MockingSample.ItemManagerTester.TestForGetItemsFomTable'
failed: System.NullReferenceException : Object reference not set to an instance of an object.
    ItemManager.cs(26,0): at MockingSample.ItemManager.GetItemsFomTable()
    ItemManager.cs(77,0): at MockingSample.ItemManagerTester.TestForGetItemsFomTable()

What should I do with the List ? How and where can I mock this if needed ?

+1  A: 

Since you haven't specified a return value, the mock item fetcher returns null, so the attempt to access resultDataTable.Rows throws.

To fix the error, tell Moq what you want it to return when you configure the expectation:

mockItemFetcher.Setup(x => x.GetItemsFromDB()).Returns(new DataTable());
Jeff Sternal