When several scenarios need similar test objects, scattered hard-coded setup creates duplication and makes shared defaults harder to maintain. The Default Instance pattern uses factory methods to create reusable default objects or object hierarchies, then lets scenarios customize them when needed. section 14.2 section 14.8
For a practical implementation:
- Keep defaults consistent and make the generator clear enough to document the team’s agreed values. section 14.2
- When the returned object is mutable, change only the attributes needed for the scenario. For immutable objects, use Object Mother to apply customizations before construction. section 14.2
Listing 14.6 Step definitions that create pizza items using the generator method
*** Support/DomainDefaults.cs ***
public static class DomainDefaults
{
public const string PizzaName = "Margherita";
public const string PizzaSize = "Medium";
public const PizzaStyle PizzaStyle = PizzaStyle.Regular;
public static PizzaItem PizzaItemDefaultInstance() #A
{
return new PizzaItem(PizzaName, PizzaSize, PizzaStyle);
}
}
*** StepDefinitions/OrderingStepDefinitions.cs ***
[Given("the customer has placed an order containing a {string} pizza")]
public void GivenTheCustomerHasPlacedAnOrderContaining(string pizzaName)
{
...
var pizzaItem =
DomainDefaults.PizzaItemDefaultInstance(); #B
pizzaItem.Name = pizzaName; #C
order.AddItem(pizzaItem);
...
}
[When("the customer places an order for {int} pizza(s) of size {string}")]
public void WhenTheCustomerPlacesAnOrderFor(int count, string pizzaSize)
{
...
for ( /* count */ )
{
var pizzaItem =
DomainDefaults.PizzaItemDefaultInstance(); #B
pizzaItem.Size = pizzaSize; #C
order.AddItem(pizzaItem);
}
...
}
[Given("the customer has placed an order")]
public void GivenTheCustomerHasPlacedAnOrder()
{
...
var pizzaItem =
DomainDefaults.PizzaItemDefaultInstance(); #B
order.AddItem(pizzaItem);
...
}See the pizza-item factory method and a step definition that changes the default pizza name. section 14.2
