EF6 DbSet<T> returns null in Moq
Add a setup for the Set<T>()
method:
mockContext.Setup(c => c.Set<CartItem>()).Returns(mockSet.Object);
Even though on the real EFContext
the property Cart
and Set<CartItem>()
refer to the same object, the mock of the context doesn't know that, so you need to tell it explicitly what to return.
Since it was a loose mock, the call to a method that hasn't been setup returns the default value, which in this case is null
. Strict mocks are nice in helping find this error, but also have maintenance costs that other folks don't want to deal with.