Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 16, 2022 08:21 am GMT

Writing unit tests for EF Core

Gday guys!

Its been a while since Ive had a good look at Entity Framework, since for the last couple of years Ive been professionally living in mostly NoSQL-land. Earlier today though, I thought Id crack open an old hobby project and add some unit tests for it. Thats easier said than done though unless you know what youre 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 youre done! The problem essentially is the DbSet<T> that you use to define your tables. Firstly, DbSet<T> is abstract, so it cant 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 Ive 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 thats it! Admittedly I havent 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 (Im dreaming of Tim Tams), its much appreciated.

Anyway, thats all from me - this might be my shortest post yet. Happy mocking!

Catch ya!


Original Link: https://dev.to/jasonsultana/writing-unit-tests-for-ef-core-4lji

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To