Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using auto-configured localdb for unit testing; how do I clean up?

I've configured an .mdf file along with a localdb connection string for use in unit tests, like this:

<connectionStrings>
        <add name="TestData" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\v11.0; AttachDBFilename='|DataDirectory|\TestData.mdf'; Integrated Security=True"/>
</connectionStrings>

Once I've configured deployment files for my test correctly, this works beautifully: a copy of the .mdf is attached to the default instance of LocalDB, and the SqlClient connects to it without a shred of configuration. It just works.

But how do I clean up afterwards? On my local box, I can periodically use SSMS to manually detach old testing databases, but on a CI server it would obviously be preferable to have the unit test clean itself up.

Is there a similarly automagic way to cause a localdb database to detach itself from the instance?

like image 510
Ben Collins Avatar asked Sep 05 '12 02:09

Ben Collins


People also ask

Can I use LocalDB in production?

LocalDB is absolutely supported in production. From the performance point of view it is identical to SQL Server Express, as they share the same database engine.

Can Ssdt project create a test environment?

Visual Studio SSDT will automatically create a test template however we need to change this unit test method. We will develop the test method according to following sample test document. We will select Pre-test option in the test condition combobox then add the following query.


1 Answers

This is how I am deleting the localDB database. The thing I don't like is that the .mdf is also removed. I overcome that by copying it to a tem directory first and using the copy to create the db.

var sc = new Microsoft.SqlServer.Management.Common.ServerConnection(your localDB SqlConnection here);
var server = new Microsoft.SqlServer.Management.Smo.Server(sc);
server.KillDatabase(dbName here);

Hope this helps Phil

like image 153
phil Avatar answered Oct 16 '22 08:10

phil