Skip to content

Creating connection strings

Jon P Smith edited this page Sep 30, 2017 · 6 revisions

3. 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 AppSettings.GetConfiguration() method

The method AppSettings.GetConfiguration() will get the configuration file using the ASP.NET Core code. You can place any setting for your unit tests

The GetUniqueDatabaseConnectionString() extention method

The method GetUniqueDatabaseConnectionString() is an extention method on an object. It uses that object's name to form a connection string based on the UnitTestConnection in you appsettings.json file, but where the database name from the UnitTestConnection connection string has the name of the object added as a suffix. See the test code below.

[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}");
}

The GetUniqueDatabaseConnectionString() extention 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