Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Entity Framework Context

I'm using the entity framework to access my database and I want to mock the database context inside my unit tests so that I can test my middle tier classes free of their dependency on real data. I know that I'm not the first to ask about this (Mocking an Entity Framework Model), but after some googling I have an instinct that it might be possible to instantiate the context based on the model's metadata alone.

Has anyone been able to do this?

like image 986
Dav Evans Avatar asked Apr 02 '09 16:04

Dav Evans


People also ask

What is mocking framework C#?

Mocking Frameworks (Moq, NSubstitute, Rhino Mocks, FakeItEasy, and NMock3) are used to create fake objects. We can stub, i.e., completely replace the body of member and function. It is used to isolate each dependency and help developers in performing unit testing in a concise, quick, and reliable way.

How do you use DbContext in unit testing?

Convert the DbSet properties on the DbContext derived class into IDbSet properties. Add a section that generates an interface for the DbContext derived class containing the IDbSet properties and any other methods (such as SaveChanges) that you'll need to mock. Implement the new interface in the DbContext derived class.

What is the benefit of mocking?

A mock means solving a test for practice following all the rules of the actual examinations. This helps a lot while appearing for the actual examination. A candidate can analyze his/her performance in the mock and make the necessary changes to avoid the same mistakes in the actual examination.

How do you mock data in C#?

Now to demonstrate the power of mocking through MoQ I will tweak the unit testing. First, I need to create an interface named IDBcontext. Instead of creating an object of DBContext at the class level, I will be injecting IDBContext in “ProcessGSTForNextOrder” method along with the order id.


2 Answers

A well known way of doing this is to use the Repository pattern. This acts as a layer over your concrete data access implementation and provides a place to inject test doubles.

like image 89
Andrew Peters Avatar answered Oct 13 '22 00:10

Andrew Peters


You can do it with just metadata, there's a good article on it, and unit testing EF in general, here.

like image 24
Steven Robbins Avatar answered Oct 13 '22 01:10

Steven Robbins