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
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.