Skip to content

Delete all test databases

Jon P Smith edited this page Nov 9, 2021 · 1 revision

Sometimes you might want to delete all the databases used in a specific

Deleting all the unit tests for one project

In a project you are likely to create a LOT of databases, and its a bit of a pain to delete them all. I have therefore created a static methods that can delete all your SQL Server and PostgreSQL test databases within your application. There are two methods that provide this feature:

  • SQL Server: DeleteAllSqlServerTestDatabases using the UnitTestConnection connection string
  • PostgreSQL: DeleteAllPostgreSqlTestDatabases using the PostgreSqlConnection connection string

These will delete all the databases who's name starts with the database name in the connection string in the appsettings.json file (see Creating connection strings for more info). So, if your SQL Server UnitTestConnection connection contains the

"Server=(localdb)\\mssqllocaldb;Database=EfCore.TestSupport-Test;...

Then when you call the DeleteAllSqlServerTestDatabases method it will wipe all the databases starting with EfCore.TestSupport-Test.

Here is a unit test, guarded by the attribute [RunnableInDebugOnly], that you should run after a change to your DbContext or entity classes.

//Run this method to wipe ALL the test databases using your appsetting.json connection string
//You need to run it in debug mode - that stops the unit test being run when you "run all" unit tests
[RunnableInDebugOnly]
public void DeleteAllSqlServerTestDatabasesOk() 
{
    var numDeleted = DatabaseTidyHelper.DeleteAllSqlServerTestDatabases();
    _output.WriteLine( "This deleted {0} databases.", numDeleted);
}

For PostgreSQL the code is the same but it uses the DeleteAllPostgreSqlTestDatabases method.

Clone this wiki locally