Mock AsNoTracking Entity Framework

前端 未结 3 808
傲寒
傲寒 2020-12-05 18:18

How do I mock AsNoTracking method?
In below example, DbContext has injected to the service class.It works fine if I remove AsNoTracking extension method from GetOrderedP

相关标签:
3条回答
  • 2020-12-05 18:41

    you can use Entity Framework Effort to mock the AsNoTracking(), also you can mock the Db Transactions and Entity State by using Effort - Official site for Effort

    0 讨论(0)
  • 2020-12-05 18:44

    Looking at the source code of the AsNoTracking() extension method:

    public static IQueryable AsNoTracking(this IQueryable source)
    {
        var asDbQuery = source as DbQuery;
        return asDbQuery != null ? asDbQuery.AsNoTracking() : CommonAsNoTracking(source);
    }
    

    Since source (your DbSet<Product> you're trying to mock) is indeed a DbQuery (because DbSet is deriving from DbQuery), it tries to invoke the 'real' (non-mocked) AsNoTracking() method which rightfully returns null.

    Try to mock the AsNoTracking() method as well:

    mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);
    
    0 讨论(0)
  • 2020-12-05 18:58

    You have:

    context.Setup(c => c.Products).Returns(mockSet.Object);
    context.Setup(m => m.Set<Product>()).Returns(mockSet.Object);
    context.Setup(c => c.Products.AsNoTracking()).Returns(mockSet.Object);
    

    But remember that extension methods are just syntactic sugar. So:

    c.Products.AsNoTracking()
    

    is really just:

    System.Data.Entity.DbExtensions.AsNoTracking(c.Products)
    

    therefore your mock setup above is meaningless.

    The question is what the static DbExtensions.AsNoTracking(source) method actually does to its argument. Also see the thread What difference does .AsNoTracking() make?

    What happens if you just remove the Setup involving AsNoTracking from your test class?

    It might be helpful to give all your mocks MockBehavior.Strict. In that case you will discover if the members the static method invokes on them, are mockable by Moq (i.e. virtual methods/properties in a general sense). Maybe you can mock the non-static method DbQuery.AsNoTracking if necessary.

    0 讨论(0)
提交回复
热议问题