c# - Unit Test Entity Framework sets connection string to bin directory instead of App_Data -



c# - Unit Test Entity Framework sets connection string to bin directory instead of App_Data -

i trying run unit tests using entity framework.

when run using debug or release set connection string so:

#if release public datacontext() : base("release") { } #else public datacontext() : base("debug") { } #endif

my connection strings in web.config 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 run asp.net mvc site.

but when go run unit tests, looks in bin directory instead of using debug connection string debug database in app_data directory, if project build against debug configuration before running tests.

the error is:

system.data.entity.core.entityexception: underlying provider failed on open. ---> system.data.sqlclient.sqlexception: cannot attach file 'd:\development\projects\myproject\myproject\bin\mydatabase.mdf

why looking in bin directory instead of using app_data path defined in connection string?

answer:

the reply set info directory in app domain in test fixture setup in base of operations 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); } }

for unit-test project, datadirectory not set automatically. seek set manually yourself:

var appdatadir = path.combine(appdomain.currentdomain.basedirectory, "../../app_data"); appdomain.currentdomain.setdata("datadirectory", appdatadir);

make sure you're invoking above code before initializing ef context.

c# asp.net-mvc entity-framework unit-testing connection-string

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -