-
Notifications
You must be signed in to change notification settings - Fork 57
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 AppSettings.GetConfiguration() will get the configuration file using the ASP.NET Core code.
You can place any setting for your unit tests
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.
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)