EF6 localdb for integration testing

entity-framework-6 localdb testing

Popular Answer

Here is what I decided to do after gathering information from many sources. First, I added the following to the App.Config of my test project.

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

Then I made 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());


According to what I understand, this starts before each exam. The |DataDirectory| used in the App.Config is updated by the SetData method to make it distinct and prevent it from attempting to utilize the same instance as the standard project.

Following that, I can either execute the migrations and then submit some test data as part of the test, or I may run an initializer that creates the test data. Keep in mind that the configuration class created by the migration must be changed from internal to public in order to conduct the migrations.

So far, this seems to work. I'm unsure of if this is the best approach or whether I can combine the migrations and then use a separate seed for the testing.

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