I am trying to run Unit Tests using the Entity Framework.
When I run using debug or release I set my connection string like so:
#if RELEASE
public DataContext()
: base("Release")
{
}
#else
public DataContext()
: base("Debug")
{
}
#endif
My Connection Strings in Web.Config look like:
<connectionStrings>
<add name="Debug" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\mydatabase.mdf;Initial Catalog=mydatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Release" connectionString="MultipleActiveResultSets=true;Net=dbmssocn;Server=my.site.com;Database=mydatabase;User ID=myuser;Password=mypass;" providerName="System.Data.SqlClient" />
</connectionStrings>
This works great when I simply run my Asp.Net MVC site.
But when I go to run Unit Tests, it looks in the bin directory instead of using the Debug connection string with the debug database in my App_Data directory, even if the project is build against the Debug configuration before running the tests.
The error I get is:
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Cannot attach the file 'D:\Development\Projects\myproject\MyProject\bin\mydatabase.mdf
Why is it looking in the bin directory instead of using the App_Data path defined in the connection string?
ANSWER:
The answer was to set the data directory in the App Domain like this in the Test Fixture Setup in my Base Test Class:
public class TestBase
{
[TestFixtureSetUp]
public void Setup()
{
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var appDataDirectory = Path.Combine(baseDirectory.Replace("\\bin", ""), "App_Data");
AppDomain.CurrentDomain.SetData("DataDirectory", appDataDirectory);
}
}