liveBook · Manning

Polymorphic driver pattern

As explained in Effective Behavior-Driven Development

A BDD automation pattern that runs the same scenarios against different application interfaces by selecting interchangeable test-driver implementations.

A team may have business scenarios that already check an application through a direct service call. To gain confidence in its REST API or user interface, the team could copy those scenarios into separate automation projects. That feels convenient when interfaces use different tools or teams, but it can duplicate preparation code and separate people working on the same behavior. section 15.6

The polymorphic driver pattern keeps the scenarios and their business language shared. Step definitions use a common driver interface; interchangeable implementations carry out the same actions through different application interfaces. Configuration selects an implementation for a test run, so the scenario need not name the technical route it takes. section 15.0 section 15.6

One authentication scenario, two routes

An authentication driver can offer Login and Register actions. One implementation sends REST requests; another calls the application service directly. Both satisfy the same driver interface, allowing the surrounding scenario automation to be reused. A UI implementation is another possible target, not an implementation shown in this example. section 15.6

Listing 15.20 Multiple implementations of the authentication driver
*** Drivers/IAuthenticationDriver.cs ***
public interface IAuthenticationDriver
{
    TestAction<LoginResponse> Login(string customerName, string password);
    TestAction<VoidReturn> Register(string customerName, string email);
}

*** Drivers/AuthenticationRestApiDriver.cs ***
public class AuthenticationRestApiDriver(RestApiContext restApiContext) : 
    IAuthenticationDriver
{
  public TestAction<LoginResponse> Login(
      string customerName, string password) =>
    new LambdaAction<LoginResponse>("Login", async () =>
        {
          var loginResponse = await restApiContext
            .ProcessRequest<LoginResponse>(
              "Login", HttpMethod.Post, "/api/auth/login", 
              new LoginRequest(customerName, password));
          restApiContext.BearerToken = loginResponse.Token;
          return loginResponse;
        });

  public TestAction<VoidReturn> Register(
      string customerName, string email) =>
    new LambdaAction("Register", async () =>
        await restApiContext.ProcessRequest<VoidReturn>(
            "Register", HttpMethod.Post, "/api/auth/register", 
            new RegisterRequest(customerName, email), 
            HttpStatusCode.Created));
}

*** Drivers/AuthenticationServiceDriver.cs ***
public class AuthenticationServiceDriver(AuthenticationService authService) 
    : IAuthenticationDriver
{
  public TestAction<LoginResponse> Login(
      string customerName, string password) =>
    new LambdaAction<LoginResponse>("Login", () =>
    {
      var result = authService.Login(customerName, password);
      return result.Successful ? 
        new LoginResponse(result.Value, customerName) :
        throw new TestActionFailedException(result.ErrorMessage);
    });

  public TestAction<VoidReturn> Register(
      string customerName, string email) =>
    new LambdaAction("Register", () =>
    {
      var result = authService.Register(customerName, email);
      if (!result.Successful)
      {
        throw new TestActionFailedException(result.ErrorMessage);
      }
    });
}

The driver listing shows how Login and Register form a shared contract while an implementation handles REST-specific details. section 15.6

To put the pattern to work:

  • Express actions in a driver interface that the step definitions can use, rather than embedding interface-specific automation in each step. section 15.0 section 15.6
  • Provide an implementation for each interface the test run needs to target. section 15.6
  • Select the implementation through configuration. In the authentication example, an environment variable determines which driver is registered before a scenario. section 15.6
Listing 15.21 Register driver implementations depending on an environment variable
*** Support/DiConfiguration.cs ***
[Binding]
public class DiConfiguration
{
  [BeforeScenario(Order = 0)]
  public void SetupDependencies(IObjectContainer scenarioContainer)
  {
    if (Environment.GetEnvironmentVariable(    #A
            "WIMP_TEST_TARGET") == "rest")
    {
      scenarioContainer.RegisterTypeAs<AuthenticationRestApiDriver,
          IAuthenticationDriver>();    #B
    }
    else
    {
      scenarioContainer.RegisterTypeAs<AuthenticationServiceDriver,
          IAuthenticationDriver>();    #C
      ...    #D
    }
  }
}

The registration listing makes the runtime choice concrete: a REST setting registers the REST driver; otherwise, the service driver is registered. section 15.6

Sharing scenarios can reduce duplicated automation and encourage teams to agree on the product behavior they are testing. It does not remove every tooling barrier: incompatible automation frameworks may still make a single solution impractical. Where the implementations can share a codebase, the pattern helps check whether behavior holds across available interfaces. section 15.6 section 15.9

How Effective Behavior-Driven Development covers it

How deep it goes
Details a shared driver contract and configuration-based registration, but does not demonstrate a UI driver implementation.
Examples
Contrasts REST and direct-service authentication drivers, with an environment variable selecting their registration before scenarios.
What it assumes
Builds on scenarios, step definitions, and test drivers while illustrating the shared driver contract through authentication actions.
What you can do after
Apply it via C# driver interfaces and dependency-injection registration to run shared scenarios against REST or direct service interfaces.
How it connects
Links test drivers, step definitions, dependency injection, REST APIs, UI automation, and direct service calls.

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.