繁体   English   中英

如何用NSubstitute模拟EF

[英]How to mock EF with NSubstitute

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

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

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

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

我不允许更改此构造函数,并且我可能会犯一些错误,我对此表示赞赏。

你是后失踪() MockMachineDBContextMockMachineDBContext().Products.AddRange( Products );

MockMachineDBContext是委托。 有关用法,请参见在NSubstitute中替代代理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM