如何模拟在被测方法中声明/初始化的对象?

时间:2010-01-15 21:56:39

标签: c# unit-testing exception nunit moq

考虑这个程序

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();
    }
}

我想测试itemFetcher.GetItemsFromDB方法在类ItemManager的方法“GetItemsFomTable()”中调用一次。这是测试

[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();
        }
    }

正如您所看到的,在测试方法

中初始化了List
List<Item> itemsList = new List<Item>();

我得到了这个例外:

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()

我该如何处理清单?如果需要,我该如何以及在哪里嘲笑这个?

1 个答案:

答案 0 :(得分:2)

由于您尚未指定返回值,因此模拟项目获取器返回null,因此尝试访问resultDataTable.Rows会抛出。

要修复错误,请在配置期望时告诉Moq您希望它返回的内容:

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