Reputation: 16156
I'm working on some automated tests (using MSTest) that create a unique database for each test case, isolating each test from the results of the previous tests (and test runs). I'm using the Microsoft DACFx tools to accomplish this. How can I remove the test database during test cleanup, so I don't rack up a huge collection? The SQL Server instance is running on localhost
.
I looked through the DACFx documentation and couldn't find any way to remove an entire database.
This is the code I use to create the database, and it would be nice if there were a way to also delete it in code, rather than by executing a SQL script:
using (var dacpac = DacPackage.Load(path)) {
instance.Deploy(dacpac, databaseName, upgradeExisting: true);
}
Upvotes: 1
Views: 1749
Reputation: 3271
I do exactly the same with creating a Test database in TestInitialize
and then removing it during TestCleanup
. For me though, the database is always called 'UnitTesting'. You could use some string substitution if your unique names are generated in C# code
In TestCleanup
I execute this script
USE [master];
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';' FROM sys.dm_exec_sessions WHERE database_id = db_id('UnitTesting')
EXEC(@kill);
/****** Object: Database [UnitTesting] Script Date: 12/05/2018 23:06:16 ******/
USE [master]
IF EXISTS(SELECT * FROM SYS.DATABASES WHERE NAME = 'UnitTesting')
DROP DATABASE [UnitTesting]
You may also want to run this script during TestInitialize
to make sure any incomplete runs don't affect the next Test Method
Upvotes: 1