-
Notifications
You must be signed in to change notification settings - Fork 56
Creating connection strings
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
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:
- A connection string with the name
UnitTestConnection
- 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 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.
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.
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)