Mock AsNoTracking Entity Framework

前端 未结 3 826
傲寒
傲寒 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:58

    You have:

    context.Setup(c => c.Products).Returns(mockSet.Object);
    context.Setup(m => m.Set()).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.

提交回复
热议问题