When scenarios share a costly external resource, initializing it for every scenario can slow test runs. Test environment initialization moves setup to a before-test-run hook; an after-test-run hook can clean up when needed. section 21.1 section 21.0
Choose when to initialize based on how scenarios use the resource:
- Use a before-test-run hook to initialize a shared resource once for the run, rather than once per scenario. section 21.1
- Defer initialization until the resource is first requested when not every run or scenario needs it. A constructor can trigger this setup, but it does not replace cleanup after the run. section 21.1 section 21.5
Listing 21.1 Using a before-test-run hook to update the database schema
*** Support/Hooks.cs ***
[Binding]
public class Hooks
{
...
[BeforeTestRun] #A
public static async Task InitializeDatabase()
{
var testConfigurationProvider = new TestConfigurationProvider();
if (!testConfigurationProvider.Database.UseStub)
{
await DatabaseDriver.UpgradeSchemaIfNeeded( #B
testConfigurationProvider.Database.ConnectionString);
}
}
}
*** Drivers/DatabaseDriver.cs ***
public class DatabaseDriver
{
public static async Task UpgradeSchemaIfNeeded( #C
string connectionString)
{
var dbContextFactory = WimpDbContextOptionsBuilder #D
.CreateDbContextFactory(connectionString);
await using var db = dbContextFactory.CreateDbContext();
await db.Database.MigrateAsync(); #E
}
...
}A C# before-test-run hook checks configuration and upgrades the database schema when a database is in use. section 21.1
