Unfortunately you are not doing it right because that article is wrong. It pretends that FakeContext
will make your code unit testable but it will not. Once you expose IDbSet
or IQueryable
to your controller and you fake the set with in memory collection you can never be sure that your unit test really tests your code. It is very easy to write a LINQ query in your controller which will pass your unit test (because FakeContext
uses LINQ-to-Objects) but fails at runtime (because your real context uses LINQ-to-Entities). That makes whole purpose of your unit testing useless.
My opinion: Don’t bother with faking context if you want to expose sets to controller. Instead use integration tests with real database for testing. That is the only way how to validate that LINQ queries defined in controller do what you expect.
Sure, if you want to call just ToList
or FirstOrDefault
on your sets your FakeContext
will serve you well but once you do anything more complex you can find a trap pretty soon (just put the string “Cannot be translated into a store expression” into Google – all these problems will appear only when you run Linq-to-entities but they will pass your tests with Linq-to-objects).
This is quite common question so you can check some other examples:
- To return IQueryable or not return IQueryable
- Unit Testing DbContext
- ASP.NET MVC3 and Entity Framework Code first architecture
- Organizationally, where should I put common queries when using Entity Framework Code First?
- Is it possible to stub Entity Framework context and classes to test data access layer?