If you’re using Entity Framework in an application that you would like to write some integration tests (note: these are not unit tests, since they touch a dependency – namely, a database), it can be a little bit challenging to get started. Here are the steps you can take to make testing entity framework with migrations work successfully.
First, grab a project that uses Entity Framework in a strongly coupled, difficult-to-unit-test manner, like the ASP.NET MVC 5 sample application MvcMovie. You’ll find the link to download the project at the top of the first page of the tutorial.
Next, add your test project. You can use whatever testing framework you like. For this example, I’ll use the built-in Unit Test Project that utilizes MSTest. Rename the default UnitTest.cs file and create an initial test like so:
namespace MvcMovie.Tests { [TestClass] public class MoviesControllerIndexShould { private readonly int MOVIECOUNT = 4; private MoviesController _moviesController; [TestInitialize] public void SetUp() { _moviesController = new MoviesController(); } [TestMethod] public void ReturnAllMoviesGivenEmptyStringParameters() { var result = _moviesController.Index(String.Empty, String.Empty) as ViewResult; var movies = result.Model as IQueryable<Movie>; Assert.AreEqual(MOVIECOUNT, movies.ToList().Count); } } }
This is a working test, once you get past all of the hurdles involved in making your tests work with a database (and EF and Migrations). Try and run it without doing anything else at this point. If you literally have done nothing but copy and paste this into your project, it probably doesn’t even compile yet. You need to add a reference to the MvcMovie project. Then, you’ll also need to add references to Mvc and eventually EF. You can do this from the Package Manager Console:
Install-Package EntityFramework Install-Package Microsoft.AspNet.WebPages
When you’re done, your packages.config file should look like this:
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="EntityFramework" version="6.0.0" targetFramework="net45" /> <package id="Microsoft.AspNet.Razor" version="3.0.0" targetFramework="net45" /> <package id="Microsoft.AspNet.WebPages" version="3.0.0" targetFramework="net45" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> </packages>
At this point, hopefully you can at least build the test project. Try running the tests. You’ll probably run into an issue with EF configuration. We don’t have any. What you need is in the MvcMovie Web.config file. Add a new App.config file to your test project, and copy the configSections, connectionStrings, and entityFramework sections from Web.config to App.config. You can remove the extra connection strings – just keep the one called MovieDBContext.
You’ll want to modify the MovieDbContext connection string. In Web.config, it will look something like this:
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MoviesRTM.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
Tests don’t typically do well with |DataDirectory| paths, so you can change this to something a bit simpler:
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;;Integrated Security=True" providerName="System.Data.SqlClient" />
Good news! At this point if you run your tests, you should get a new error. Progress! Sometimes trying to do something simple like writing a test feels like this:
Clik here to view.

What programming feels like
Most likely the error you receive now is complaining that the DbContext is set up for migrations, but it couldn’t find them or you didn’t run them or something like that. If you search for the error message, you should quickly find that you need to run Update-Database to fix it (in fact, to get the MvcMovie project to run, you need to do this as well, for that project). So, you jump into Package Manager Console and run the command for your test project and get:
PM> Update-Database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. No migrations configuration type was found in the assembly 'MvcMovie.Tests'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
So close! Luckily, there is a way to get this to work, without the need for you to copy your DbContext and/or migration config classes from the MvcMovie project (which would be bad, since then you would need to keep your test copies in sync with your production copies). There’s a great guide to the parameters on entity framework migrations that shows you what you need. Here’s the line that works:
PM> update-database -ProjectName MvcMovie -StartUpProjectName MvcMovie.Tests Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying explicit migrations: [201309280158276_Initial, 201309280212154_Rating, 201309302013486_DataAnnotations]. Applying explicit migration: 201309280158276_Initial. Applying explicit migration: 201309280212154_Rating. Applying explicit migration: 201309302013486_DataAnnotations. Running Seed method.
Assuming you’re still with me, you should now be able to run your first integration test on the project! To recap, the steps you need to take are:
- Add a test project
- Reference the system-under-test project
- Add required Nuget packages (EF, WebPages)
- Add required configuration (App.config, 3 sections)
- Change the connection string
- Run Update-Database using correct parameters
If you’re struggling with this kind of testing and want to be able to unit test your application without the need for a lot of extra testing infrastructure, I recommend my Pluralsight courses on SOLID Principles and Domain-Driven Design. Good luck!
The post Integration Testing Entity Framework with Migrations appeared first on Falafel Software Blog.