【问题标题】:How to mock EF with NSubstitute如何使用 NSubstitute 模拟 EF
【发布时间】:2017-07-19 09:19:39
【问题描述】:

我的任务是创建一个测试脚本,该脚本将(使用实体框架)在表中查找值(如果存在)。

我必须使用的代码有这个构造函数:

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

最后一行显示“无法解析符号“产品”的哪些错误。

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

【问题讨论】:

    标签: c# entity-framework unit-testing nsubstitute


    【解决方案1】:

    你在MockMachineDBContext().Products.AddRange( Products );中的MockMachineDBContext之后缺少()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      相关资源
      最近更新 更多