I have an MDF file that I\'m attaching to my local SQL server during testing with MSTEST and I don\'t want to have to go delete those temporary databases by hand after I\'ve
I. Create Resources file (Resources.rsx) and write sql queries:
DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'{0}'
DECLARE @SQL varchar(max)
SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
EXEC(@SQL)
IF EXISTS(select * from sys.databases where name='{0}')
DROP DATABASE [{0}]
II. Add MsSqlDatabaseTestsHelper class into the test project
public class MsSqlDatabaseTestsHelper
{
private readonly string _connectionString;
public MsSqlDatabaseTestsHelper(string connectionString)
{
_connectionString = connectionString;
}
private void ExecuteNonQuery(string sql)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
public void CreateDatabase(string databaseName)
{
ExecuteNonQuery("CREATE DATABASE {0}".Set(databaseName));
}
public void DropDatabase(string databaseName)
{
try
{
ExecuteNonQuery(Resources.SQL_KillConnections
.Set(databaseName));
}
catch (Exception)
{
throw new Exception("Can't kill database '{0}' connections"
.Set(databaseName));
}
try
{
ExecuteNonQuery(Resources.SQL_DropDatabaseIfExists
.Set(databaseName));
}
catch (Exception)
{
throw new Exception("Can't drop database '{0}'"
.Set(databaseName));
}
}
}
III. Use database helper in your unit tests
[TestFixture]
public class CmsPageRepositoryTests
{
private readonly MsSqlDatabaseTestsHelper _msSqlDatabaseTestsHelper =
new MsSqlDatabaseTestsHelper(ConnectionStringWithoutDatabase);
private const string ConnectionStringWithoutDatabase =
@"server=.\SqlExpress;uid=sa;pwd=1;";
private const string DatabaseName = "TestPersistence";
[SetUp]
public void SetUp()
{
_msSqlDatabaseTestsHelper.DropDatabase(DatabaseName);
_msSqlDatabaseTestsHelper.CreateDatabase(DatabaseName);
}
[TearDown]
public void TearDown()
{
_msSqlDatabaseTestsHelper.DropDatabase(DatabaseName);
}
[Test]
public void TestSomethingWithDatabaseUsing()
{
}
}