简体   繁体   English

如何用NSubstitute模拟EF

[英]How to mock EF with NSubstitute

I have been tasked at work to create a test script that will (using entity framework) look-up a value in a table if existing. 我的工作是创建一个测试脚本,该脚本将(使用实体框架)在表中查找值(如果存在)。

The code I have to work with has this constructor: 我必须使用的代码具有以下构造函数:

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

My method to unit test could be something like this: 我的单元测试方法可能是这样的:

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

so, going by the examples when Googling I am supposed to do this: 因此,按照谷歌搜索时的示例操作,我应该这样做:

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

But in order to pass to my constructor I have to modify this to: 但是为了传递给我的构造函数,我必须将其修改为:

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

which errors on the last line saying 'cannot resolve symbol 'Products'. 最后一行显示“无法解析符号“产品”的错误。

I am not allowed to change this constructor and I appreciate I may be making some mistakes. 我不允许更改此构造函数,并且我可能会犯一些错误,我对此表示赞赏。

You are missing () after MockMachineDBContext in MockMachineDBContext().Products.AddRange( Products ); 你是后失踪() MockMachineDBContextMockMachineDBContext().Products.AddRange( Products );

MockMachineDBContext is delegate. MockMachineDBContext是委托。 For usage also see Substituting for delegates in NSubstitute . 有关用法,请参见在NSubstitute中替代代理

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

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