How to set up LocalDb for unit tests in Visual Studio 2012 and Entity Framework 5

杀马特。学长 韩版系。学妹 提交于 2019-11-29 20:50:21
zbw911

Try:

AppDomain.CurrentDomain.SetData(
  "DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""));

This will Create Db File on /bin/Debug/yourdbname.mdf

Jupaol

I would use:

// Declare this property - this is set by MSTest
public TestContext TestContext { get; set; }

// In test initialization - note the signature should be exactly this
// A static void method with one argument of type TestContext 
[ClassInitialize]
public static void SetUp(TestContext context)
{
   AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(context.TestDeploymentDir, string.Empty));
}

You could get problems using AppDomain.CurrentDomain.BaseDirectory, instead use: context.TestDeploymentDir

Keep in mind that for a test project:

AttachDBFilename=|DataDirectory|

means it will look in your output /bin/debug folder for a unit test as opposed to the App_Data folder in your web/production/whatever app.

You need to do two things 1. Move the database file OUT OF your App_Data folder to your root of your test app. 2. Highlight your database so you get your properties window in Visual Studio. Set the build action to "Content" so it will get copied to your output folder when you run the project.

Voila.

Davide Icardi

I suggest to use this code (based on the answer of Jupaol):

[ClassInitialize]
public static void SetUp(TestContext context)
{
    AppDomain.CurrentDomain.SetData(
        "DataDirectory", 
        context.TestDeploymentDir);
}

Usually this will create your database inside TestResults\<test run>\Out\ folder of your solution.

I found your question while searching for answer to the problem. Using EntityFramework with nUnit in a separate project, I had to change the App.config

looked like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!