ASP.NET MVC Web API: Mockup Entity Framework using Moq

Download from github

The following example shows how mockup Entity Framework in a ASP NET MVC Web API project using Moq.

ASP.NET MVC Web API: Mockup Entity Framework using Moq

Defining the model:

Firstly, you need to define your model. The model will be referenced by your ADO.NET Entity Data Model, the following code describes the two model classes that are used in this demo:

  • Location
  • Drink

Model\Drink.cs

Model\Location.cs

Defining Entity framework code first

When you create new ADO.NET Entity Data Model you can choose different Model contents, the following demo uses Empty code first content. You also need to add the two DbSets to your Entity Data Model:

Repository\databaseEF.cs

Defining WebAPI Controllers

The following code defines the controllers that are part of your WebAPI. The code defines two controllers: DrinksController and LocationsController.
DrinksController contains the method GetByLocId that accepts the location id and returns all drinks cointained in that locations. LocationsController contains a method named Get that returns the location using the location id.

Controllers\DrinksController.cs

Controllers\LocationsController.cs

Defining controllers tests

Usually, you should create a different project for Unit test classes and methods: I’ve created a class library project that contains two Test class, one for each web api controller: Controllers/LocationsControllerTests.cs and Controllers/DrinksControllerTests.cs;
The following project needs to refers the Moq library, we can use Nuget to install the package:

Install-Package Moq

.

The following code shows the implementation of the DrinksControllerTests.cs:

Firstly, I’ve initialized a IQueryable collection of data:

I’ve also initialized the mock set that refers model class, and I’ve initialized the mock context using my Repository type:

I’ve setted up mock context using the mock Set:

Finally, I’ve initialized Web API controller using Mock Context, and I’ve tested my web method using the Assert.AreEqual method:

Controller/DrinksControllerTests.cs