ASP.NET Core & EF Core 2.0 Testing

Problem

How to perform unit and integration testing of ASP.NET Core and EF Core.

Solution

Note: the sample code contain a lot more tests, I would suggest to download and play with it. Here I will list few tests to demonstrate how testing works.

Testing MVC

Add MVC controller with action methods:

Add test to verify ViewResult is returned:

Add test to verify status code result (e.g. NotFound) is returned:

Add test to verify RedirectToAction is returned:

Add a test to verify ModelState errors don’t save and return back the view:

Testing API

Add API controller with action methods:

Add a test to verify OkObjectResult is returned:

Add a test to verify CreatedAtRouteResult is returned:

Testing EF

Add a repository (implementation in sample code):

The repository will work with a DbContext:

Initialise with test data:

Now you could test various methods of repository, e.g. test GetList() method:

Integration Testing

Create a base class for integration test classes:

Create a controller to test MVC/API:

Discussion

The single biggest selling point of MVC architecture in general and ASP.NET Core in particular is that it makes testing much simpler. ASP.NET team has done a great job in making a framework that is pluggable, thus enabling testing of controllers, repositories and even the entire application a breeze.

Unit Testing

Unit Testing ASP.NET Core and API controllers is not very different than testing any other class in your application. The sample code contain a lot more tests to show examples of type of tests you could perform e.g.:

  • Verify correct IActionResult is returned, e.g. ViewResult, RedirectAtRouteResult
  • Verify correct view name is returned
  • Verify correct model is returned
  • Verify correct HTTP status code is returned e.g. NotFoundResult, BadRequestResult
  • Verify model state behaviour e.g. not saving record and returning the view.
  • Verify controller dependencies are being called.

Testing Entity Framework

You could test EF using in-memory database, you’ll need package Microsoft.EntityFrameworkCore.InMemory that gives you UseInMemoryDatabase extension method on DbContextOptionsBuilder. With these pieces in place you could now create an in-memory DbContext:

Integration Testing

Remember that ASP.NET Core application is just a console application that sets up web server to listen to HTTP requests. We can setup a test web server using TestServer class and use HttpClient to send requests to it:

 

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.Testing

Leave a Reply