Skip to content

Creating connection strings

Jon P Smith edited this page Jan 4, 2021 · 6 revisions

Helpers to create connection strings with a unique database name

The xUnit unit test library will run unit test classes in parallel. This means you need class-unique databases to allow the unit tests not to clash. I have a number of methods to help with this, but first you must add a appsettings.json

Specifying the base database connection string

If you are going to use this library to help create SQL Server databases, then you need to place an appsettings.json file in the top-level directory of you test project. The file should contain:

  1. A connection string with the name UnitTestConnection
  2. The name of the database in that connection string must end with Test. That is a safety feature (see later)

Click here for an example of the appsettings.json file.

The GetUniqueDatabaseConnectionString() extention method

The method GetUniqueDatabaseConnectionString() is an extension method on an object, typically the unit test class you are running in - see code below. This means the database name is unique to unit test class it is running in. This is useful because xUnit runs all the test classes at once, and you need a database that is unique to each test class.

It returns a connection string based on the connection string with the name UnitTestConnection in your appsettings.json file, but with the database name being a combination of the Database name in the connection and the name of the object as a suffix.

[Fact]
public void GetTestConnectionStringOk()
{
    //SETUP
    var config = AppSettings.GetConfiguration();
    var orgDbName = new SqlConnectionStringBuilder(config.GetConnectionString(AppSettings.UnitTestConnectionStringName)).InitialCatalog;

    //ATTEMPT
    var con = this.GetUniqueDatabaseConnectionString();

    //VERIFY
    var newDatabaseName = new SqlConnectionStringBuilder(con).InitialCatalog;
    newDatabaseName.ShouldEqual ($"{orgDbName}_{this.GetType().Name}");
}

NOTE: For safety reasons the GetUniqueDatabaseConnectionString() extension method insists that the database name ends with Test. This is there to stop you deleting/overwriting databases that might have real data in it.

Making a connection string unique within a class

The GetUniqueDatabaseConnectionString() extension method takes one, optional parameter, which it will add onto the database name. For instance, replacing the call in the about unit test with

this.GetUniqueDatabaseConnectionString("ExtraName");

would result in a database name now having an additional suffix of .ExtraName. This allows you to make method-level unique database names.

Clone this wiki locally