liveBook · Manning

Test driver pattern

As explained in Effective Behavior-Driven Development

A pattern that provides an outcome-oriented interface to test automation while encapsulating the technical details of interacting with an application component.

When several scenarios need to log in, copying the same HTTP request into each step definition makes the tests harder to change. It also mixes two jobs: deciding what a scenario expects and knowing how to operate the application. A test driver separates them. Step definitions make testing decisions; the driver handles the technical details of interacting with a component. section 15.2

For authentication, a driver can offer a login operation instead of making every step definition construct a request and call a REST endpoint. A step definition can then choose the customer credentials and check the result. Other step definitions can reuse the same driver without calling one another—a shortcut that can produce unexpected passes or failures when the steps make different testing decisions. section 15.2

Listing 15.5 First version of the driver class
*** Drivers/AuthenticationApiDriver.cs ***
public class AuthenticationApiDriver(AppHostingContext appHostingContext)
{
  public async Task<HttpResponseMessage?> PerformLogin(
      string customerName, string password)
  {
    var data = new LoginRequest(    #A
        customerName, password);
    return await appHostingContext.AppHost.CreateClient()
      .PostAsJsonAsync("/api/auth/login", data);    #B
  }
}

The first authentication driver gathers request construction and the REST call in one place; it still returns the raw HTTP response. section 15.2

Listing 15.6 Step definition class update to use the driver
*** StepDefinitions/AuthenticationStepDefinitions.cs ***
public class AuthenticationStepDefinitions(
    AuthenticationApiDriver authApiDriver)
{
  private HttpResponseMessage? loginApiResponse;

  [Given("the customer is authenticated")]
  public async Task GivenTheCustomerIsAuthenticated()
  {
    var response = await authApiDriver.PerformLogin(    #A
        DomainDefaults.CustomerName, DomainDefaults.Password);
    Assert.AreEqual(HttpStatusCode.OK,    #B
        response.StatusCode);
  }

  [When("the customer attempts to log in with a wrong password")]
  public async Task WhenTheCustomerAttemptsToLogInWithAWrongPassword()
  {
    loginApiResponse = await authApiDriver    #A
      .PerformLogin(DomainDefaults.CustomerName, 
          DomainDefaults.WrongPassword);
  }

  [Then("the login should fail with {string}")]
  public async Task ThenTheLoginShouldFailWith(string expectedMessage)
  {
    Assert.IsNotNull(loginApiResponse);
    Assert.AreNotEqual(HttpStatusCode.OK,    #B
        loginApiResponse.StatusCode);
    var errorMessage = await loginApiResponse.Content.ReadAsStringAsync();
    StringAssert.Contains(errorMessage, expectedMessage,
        "Login should fail with the right error message");
  }
}

The corresponding step definitions delegate login to the driver while retaining their scenario-specific assertions. section 15.2

The useful boundary is an outcome-oriented interface, not merely a new home for duplicated code. A driver can detect an invalid result and report a failed test action rather than leave every caller to interpret the response. Where an action may legitimately have different expected outcomes, keep performing the action separate from verifying which outcome was expected. Shared infrastructure details needed by multiple drivers belong in an infrastructure layer. section 15.2 section 15.9

How Effective Behavior-Driven Development covers it

How deep it goes
Develops the pattern through a REST login driver and revised step definitions, including a later version that detects invalid results.
Examples
Uses customer authentication scenarios, a login REST request, and step definitions that delegate to an authentication driver.
What it assumes
Assumes familiarity with scenarios and step definitions; demonstrates the driver boundary through a concrete authentication example.
What you can do after
Build it from scratch: move component interaction into a reusable driver while keeping scenario decisions in thin step definitions.
How it connects
Connects step definitions and REST API automation to the Infrastructure Layer and Attempt Action patterns.

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.