When step definitions live in different classes, their instance fields cannot share data. A context class is simple storage with settable properties that both classes can access, such as the authenticated customer’s name. section 13.2
Keep shared data tied to one scenario:
- Inject the context class into each step-definition class that needs it. section 13.2
- Create a fresh instance for each scenario and discard it when that scenario completes; static fields can break scenario isolation. section 13.2
Authentication and ordering
An authentication step stores the customer name in a shared context; ordering steps use it when placing or cancelling that customer’s order. section 13.2
Listing 13.4 Using an injected context class for authenticated customer name
*** Support/AuthenticationContext.cs ***
public class AuthenticationContext
{
public string? AuthenticatedCustomerName { get; set; }
}
*** StepDefinitions/AuthenticationStepDefinitions.cs ***
[Binding]
public class AuthenticationStepDefinitions( #A
AuthenticationContext authContext)
{
[Given("the customer {string} is authenticated")]
public void GivenTheCustomerIsAuthenticated(string customerName)
{
AuthenticationService.Login(customerName);
authContext.AuthenticatedCustomerName =
customerName; #B
}
}
*** StepDefinitions/OrderingStepDefinitions.cs ***
[Binding]
public class OrderingStepDefinitions( #A
AuthenticationContext authContext)
{
private int placedOrderNo;
[Given("the authenticated customer has placed the order #{int}")]
public void GivenTheAuthenticatedCustomerHasPlacedTheOrder(int orderNo)
{
OrderService.PlaceOrder(
authContext.AuthenticatedCustomerName, #C
orderNo, "Margherita");
placedOrderNo = orderNo;
}
[When("the authenticated customer cancels the placed order")]
public void WhenTheAuthenticatedCustomerCancelsThePlacedOrder()
{
OrderService.CancelOrder(
authContext.AuthenticatedCustomerName, #C
placedOrderNo);
}
...
}See an injected authentication context shared by authentication and ordering step definitions. section 13.2
