Visual studio 2010 如何使用每个MSTest单元测试运行的新数据库实例
我正在使用VisualStudio2010下的MSTest测试一个ASP.NETMVC3项目。我有一个SQL Express 2005数据库,我希望它使用,我希望每次都有一个新的数据库实例,从项目中包含的模板复制。虽然我有相当标准的要求,但我无法实现 我创建了一个.testsettings文件,该文件支持部署,我的连接字符串如下所示:Visual studio 2010 如何使用每个MSTest单元测试运行的新数据库实例,visual-studio-2010,ado.net,mstest,sql-server-express,Visual Studio 2010,Ado.net,Mstest,Sql Server Express,我正在使用VisualStudio2010下的MSTest测试一个ASP.NETMVC3项目。我有一个SQL Express 2005数据库,我希望它使用,我希望每次都有一个新的数据库实例,从项目中包含的模板复制。虽然我有相当标准的要求,但我无法实现 我创建了一个.testsettings文件,该文件支持部署,我的连接字符串如下所示: <add name="MyDb" connectionString="Data Source=.\SQLEXPRESS2005;Database=MyDbT
<add name="MyDb" connectionString="Data Source=.\SQLEXPRESS2005;Database=MyDbTest;AttachDBFilename=|DataDirectory|MyDbTest.mdf;User Instance=true;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
Test method ... threw exception: System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.EntityException: The underlying provider failed on Open.
---> System.Data.SqlClient.SqlException: Database '...\bin\Debug\MyDbTest.mdf' already exists. Choose a different database name. Cannot attach the file '...\Out\MyDbTest.mdf' as database 'MyDbTest'.
中接受的答案表示删除“Database=”connection string参数。但是,如果我这样做,它将失败,并出现以下错误:
Test method ... threw exception:
System.InvalidOperationException: Unable to complete operation. The supplied SqlConnection does not specify an initial catalog.
如何使其工作?到目前为止,我已经想出了一种在运行时、测试程序集初始化时更改DB名称的方法。这需要进一步的破解——使用反射来支持在运行时修改配置() 编辑:事实上甚至比这更糟糕:我必须在每个需要新数据库的测试开始时调用
TestHelper.RandomizeDbName()
,否则它会从以前的测试中得到剩余的数据
[TestClass]
public static class TestHelper
{
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
RandomizeDbName();
}
private static void RandomizeDbName()
{
// Get the DB connection string setting
var connStringSetting = ConfigurationManager.ConnectionStrings["TheDbSetting"];
// Hack it using Reflection to make it writeable
var readOnlyField = typeof(ConfigurationElement).GetField("_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
readOnlyField.SetValue(connStringSetting, false);
// Randomize the DB name, so that SQL Express doesn't complain that it's already in use
connStringSetting.ConnectionString = connStringSetting.ConnectionString.Replace(
"Database=MyTestDb", "Database=MyTestDb_" + new Random().Next());
}
}