简体   繁体   中英

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

MockMachineDBContext is delegate. For usage also see Substituting for delegates in NSubstitute .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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