G’day guys!
It’s been a while since I’ve had a good look at Entity Framework, since for the last couple of years I’ve been professionally living in mostly NoSQL-land. Earlier today though, I thought I’d crack open an old hobby project and add some unit tests for it. That’s easier said than done though unless you know what you’re doing, since DbContext
by default is not easily unit testable.
Bro, do you even Moq?
I hear ya! It should be as simple as extracting an interface out of your context, mocking it with Moq and you’re done! The problem essentially is the DbSet<T>
that you use to define your tables. Firstly, DbSet<T>
is abstract, so it can’t be newed. On top of that, there are a whole plethora of methods on it that are a pain to mock - ToListAsync()
, Where()
chaining, IQueryable<T>
logic, unions and other set operations and more. If I remember correctly, there was a Microsoft article published years ago which gave you an implementation for what was essentially a mockable DbSet<T>
, but I’ve found a better solution: Moq.EntityFrameworkCore
.
You can have a look at the official howto on Github, but the gist of it is:
var mock = new Mock<IYourDbContext>();
mock.Setup(m => m.Customers)
.ReturnsDbSet(_customers); // This magic comes from Moq.EntityFrameworkCore
And that’s it! Admittedly I haven’t tested it thoroughly, but for the simple-ish test cases that I have, it works like a dream. Looking at the source code interestingly looks quite similar to the Microsoft article, but even if it is just taking what Microsoft gave us and packaging it into a nice, easily-consumable chunk of nuget (I’m dreaming of Tim Tams), it’s much appreciated.
Anyway, that’s all from me - this might be my shortest post yet. Happy mocking!
Catch ya!