I now want to write some tests and I'm going to mock the DbContext using NSubstitute. I first try something like this:
The problem is that the DbSet constructor is internal (as of EF4 Code First CTP5). So, let's abstract our DB access to a simple interface and replace DbSet<T> with the IQueryable<T> interface, ending up with the below:
This interface can be implemented like so:
Now all we need to do is to use an implementation of IQueryable<T> in our mock. I'm going to use EnumerableQuery<T> which gives me the following test that now passes:
I'm new to NSubstitute but it seem to be the lowest friction mocking library out there. Just perfect for use with Entity Framework 4 Code First - certainly the lowest friction ORM there is today!
Note that we could have used the repository pattern to wrap the DbContext instead of a simple interface, the approach is almost identical.
Update: Ro Miller has an alternative approach using fakes that does a better job of surfacing IDbSet