liveBook · Manning

Test environment initialization

As explained in Effective Behavior-Driven Development

A pattern for efficiently initializing external resources shared by tests and cleaning them up when needed.

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

How Effective Behavior-Driven Development covers it

How deep it goes
Explains test-run hooks and on-demand initialization, with database setup examples and a limitation on replacing cleanup hooks.
Examples
Uses database schema migration at test-run startup and constructor-triggered initialization on first use.
What you can do after
Configure shared-resource setup once per test run, clean it up afterward when needed, or defer setup until first use.
How it connects
Connects shared-resource initialization with Scenario Resource and Resource Pooling, which address resource lifetime and reuse.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Effective Behavior-Driven Development. The section links point to the parts of the book it draws on.