I have used this code and it works well, but if you arre using DbFunctions, those are impossible to test with mocks. My suggestion is to use this where it makes sense, but know that you will not get complete code coverage especially if you use DbFunctions or Execute any SQL commands directly.
Another thing to consider is to not use the ORM for large transactions. For large selects, it's ok, but if you are doing any large updates, inserts or deletes, consider side-stepping the ORM and go for a more performant solution.
- You might need to implement GetHashCode (return an Id) and Equals (compare Id's) in order for the HashSet within InMemorySet to update properly.
- There are other things you may need to do to get testing with Moq to work with Entity Framework.
- I use NUnit instead of MS Testing Framework since NUnit has
[TestCase()]
(as of 6, 2015) - Don't forget to use
mock.Object
. - Don't forget to setup your mocks like this
mockDb.Setup(x => x.Entities).Returns(entities);
where entities is anInMemorySet<TEntity>()
; - Using
new Mock<TEntity> { CallBase = true };
is very handy such that you do not need to "Setup
" all of the methods of the mocked object. mockEntity.SetupAllProperties();
is also convenient, such that you can assign to properties instead of calling "Setup().Returns
".