如何使用 NSubstitute 模拟 EF

How to mock EF with NSubstitute

我的任务是创建一个测试脚本,该脚本将(使用 entity framework)在 table 中查找一个值(如果存在)。

我必须使用的代码具有此构造函数:

public PostProductHelper(
    Func<IMachineDBContext> contextFactory )
{
    _contextFactory = contextFactory;
}

我的单元测试方法可能是这样的:

public string CheckAndRemoveProductNameFileExtIfExists(
    string productName )
{
    using ( var ctx = CreateContext() )
    {
        return ctx.Products.FirstOrDefault( d => d.Name == productName);
    }
}

因此,在谷歌搜索时按照示例进行操作我应该这样做:

MockProductRepository = Substitute.For<IProductRepository>();
MockMessagePublicationService = Substitute.For<IMessagePublicationService>();
MockMachineDBContext = Substitute.For<IMachineDBContext>(););

var Products = new List<Product>
{
    new Product { Name = "BBB" },
    new Product { Name = "ZZZ" },
    new Product { Name = "AAA" },
}.AsQueryable();

MockMachineDBContext.Products.AddRange( Products );

但是为了传递给我的构造函数,我必须将其修改为:

MockProductRepository = Substitute.For<IProductRepository>();
MockMessagePublicationService = Substitute.For<IMessagePublicationService>();
MockMachineDBContext = Substitute.For<Func<IMachineDBContext>>();

var Products = new List<Product>
{
    new Product { Name = "BBB" },
    new Product { Name = "ZZZ" },
    new Product { Name = "AAA" },
}.AsQueryable();

MockMachineDBContext.Products.AddRange( Products );

最后一行出现“无法解析符号 'Products'”的错误。

不允许我更改此构造函数,我很感激我可能会犯一些错误。

您在 MockMachineDBContext().Products.AddRange( Products );

中的 MockMachineDBContext 之后缺少 ()

MockMachineDBContext 是委托。 用法另见 Substituting for delegates in NSubstitute.