EF6 localdb for integration testing

entity-framework-6 localdb testing


I am developing a WPF application which requires some database access. For development purposes I am using localdb with database migrations enabled and EF6.

What I cannot figure out is how do I configure a separate localdb database for integration tests inside a VS2013 test project and run the database migrations to bring it up to date and then seed it with data.

5/7/2015 3:21:27 AM

Popular Answer

Here's what I've ended up doing based off information from several sources. First, in the App.Config of my test project I've added the following

    <add name="YourContextName" connectionString="Data Source=(localdb)\mssqllocaldb;Integrated Security=true;AttachDBFilename=|DataDirectory|\databasename.mdf"
   providerName="System.Data.SqlClient" />    

Then I created the following class:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.Entity;
using MyProject.Model.Entities;
using MyProject.Migrations;

namespace IntegrationTests
    public class DatabaseInitializer : DropCreateDatabaseAlways<MyProjectDataContext>

    public class Initalize
        public static void AssemblyInit(TestContext context)
            AppDomain.CurrentDomain.SetData("DataDirectory", context.TestDeploymentDir);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyProjectDataContext, Configuration>());

            //Database.SetInitializer(new DatabaseInitializer());


My understanding is that this runs before each test run. The SetData call updates the |DataDirectory| used in the App.Config so that it is unique and doesn't try to use the same instance as the normal project.

From there I have the choice of either running the migrations and then supplying some test data as part of the test or to run an initializer that sets up the test data. Note that to run the migrations the configuration class generated by the migration must be changed from internal to public.

This seems to work so far. Not sure if this is the best way or if I can combine the migrations and then run a different seed for the tests.

5/7/2015 9:48:53 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow