UnitTest-模拟时出现NullException问题

本文关键字:NullException 问题 模拟 UnitTest- | 更新日期: 2023-09-27 18:22:10

我正试图在[TestInitialize]中进行模拟设置,并将其作为模拟对象放入列表中。

为什么我在下面得到一个System.NullReferenceException。我做错了什么?我正在使用moq和ninject。

[TestClass]
public class RepoTests
{
    private Mock<ISellBuyPipeLineRepo> _mock;
    private List<Product> _products;
    [TestInitialize]
    public void Init()
    {
        _products = new List<Product>()
        {
            new Product(){ProductId = 1, StockQuantity = 10 },
            new Product(){ProductId = 2, StockQuantity = 20 }
        };
        _mock = new Mock<ISellBuyPipeLineRepo>();
        _mock.Setup(o => o.Products).Returns(_products); 
    }
}

UnitTest-模拟时出现NullException问题

在使用变量_mock之前,您仍然需要初始化它:

this.__mock = new Mock<ISellBuyPipeLineRepo>();

有关概述,请参见快速启动。