QA AND TEST AUTOMATION · PART 7 · BDD AND FRAMEWORK DESIGN · DESIGN · 70 OF 112

Design Patterns in Test Automation: Factory, Builder

The design patterns that keep test frameworks clean, each with a ShopRung example in Java: factory for drivers, builder for test data, fluent interfaces, facade for flows, strategy for environments and browsers, the singleton and why to be careful with it, decorators and listeners for logging, and when the screenplay pattern fits. Plus the SOLID ideas behind them.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Factory
  • builder
  • fluent and facade
  • strategy
  • decorator and listeners
  • careful singleton
  • screenplay
  • SOLID

Notes

Factory

The factory pattern puts the decision of which object to create in one place. A driver factory reads the configuration and returns a Chrome driver, a Firefox driver, or a remote driver for a Selenium grid, with the right options. Tests just ask the factory for a driver. Adding Edge, or a cloud grid, means changing one method instead of every test.

DriverFactory
static WebDriver create(Config c) {
  return switch (c.browser()) {
    case "firefox" -> new FirefoxDriver(
      firefoxOptions(c));
    case "remote" -> new RemoteWebDriver(
      c.gridUrl(), chromeOptions(c));
    default -> new ChromeDriver(
      chromeOptions(c));
  };
}
// tests: DriverFactory.create(cfg)

Builder

The builder pattern creates objects step by step with readable method names. An order builder starts with sensible defaults, and a test changes only the fields it cares about: for customer Alice, with four notebooks, with the coupon save ten, then build. Compare that with a constructor taking eight arguments in a row. Builders make test data intention revealing and stop tests breaking when a new field is added.

A test data builder
Order order = anOrder()
    .forCustomer("alice@shoprung.test")
    .with(NOTEBOOK, 4)
    .withCoupon("SAVE10")
    .build();

every field has a default:
  a test sets only what it is
  about, here the coupon
records: new Order(...) with 8
  arguments is unreadable

Fluent and facade

Two related patterns. A fluent interface returns an object from each step so calls chain like a sentence, as the page objects in the Selenium lab did: open, add to cart, open the cart, apply the coupon. A facade hides a long flow behind one simple call: buy, for Alice, four notebooks with save ten, which logs in, adds, applies and orders. Tests that are not about checkout use the facade and stay short.

Fluent page objects + a facade
// fluent: each step returns the
// next page
products.open()
  .addToCart("Clean Code ...", "1")
  .openCart().applyCoupon("save10");

// facade: one call for a flow
Order o = checkout.buy(alice,
  NOTEBOOK, 4, "SAVE10");
// = login + add + coupon + order

Strategy

The strategy pattern defines a family of interchangeable behaviours behind one interface. A login strategy can be a UI login that fills the form, or an API login that puts the token into local storage, as in the Selenium lab. Configuration picks one, and tests do not change. The same idea switches environments, test data sources, or wait policies.

Login strategy
interface LoginStrategy {
  void logIn(WebDriver d, User u); }

class UiLogin implements ...
  // fills the form
class ApiLogin implements ...
  // token into localStorage

LoginStrategy login =
  cfg.fastLogin() ? new ApiLogin()
                  : new UiLogin();

Decorator and listeners

A decorator wraps an object to add behaviour while keeping the same interface. Selenium four ships one: the event firing decorator wraps a driver with a listener that is called before and after actions, here logging every click. Tests still use a normal web driver. Test runner listeners, like JUnit extensions or TestNG listeners, apply the same idea to tests: screenshots on failure, timing, reporting.

Log every action
WebDriverListener logger =
  new WebDriverListener() {
    public void beforeClick(
        WebElement e) {
      log.info("click {}", e); } };

WebDriver driver = new
  EventFiringDecorator<>(logger)
    .decorate(new ChromeDriver());
// same driver API, plus logging

Singleton

The singleton pattern gives one shared instance. It is fine for read only configuration loaded once. It is a classic mistake for web drivers: one static driver shared by every test leaks state between tests and makes parallel runs collide. If code needs a driver per thread, use a thread local, or better, create a driver per test through the factory and pass it in.

Be careful
  • OK: read-only Config, loaded once
  • NOT OK: a static singleton WebDriver shared by all tests → parallel runs collide → state leaks between tests
  • if you need one per thread: ThreadLocal<WebDriver> or a driver per test

Screenplay

The screenplay pattern models users instead of pages. An actor, Alice, has abilities like browsing the web or calling APIs, performs tasks like adding to cart and applying a coupon, and asks questions like the cart total. It scales well for large suites with many journeys and is used by Serenity BDD. For small and medium suites, page objects with flows are usually simpler.

Screenplay, briefly
alice.attemptsTo(
  AddToCart.the(NOTEBOOK, 4),
  ApplyCoupon.code("SAVE10"));
alice.should(seeThat(
  CartTotal.displayed(),
  equalTo("$49.99")));

actors HAVE abilities (browse,
  call APIs), DO tasks, ASK
  questions; used by Serenity BDD

SOLID for tests

The patterns rest on the SOLID principles. Single responsibility: the cart page and the header are separate classes. Open for extension: a new browser means a new factory case, not edits to tests. Substitution: any login strategy works where a login strategy is expected. Small interfaces. And dependency inversion: tests depend on interfaces like a login strategy or a shop API, not on concrete classes.

SOLID, briefly
  • S one reason to change per class (CartPage ≠ Header)
  • O add a browser without editing tests (factory)
  • L any LoginStrategy works
  • I small interfaces
  • D tests depend on interfaces (LoginStrategy, ShopApi), not concrete classes

Common mistakes

Pattern mistakes. Using patterns for their own sake, which adds indirection without value. A static singleton driver. Builders with no defaults, so tests still set every field. Facades that hide assertions. Deep inheritance chains instead of composing small objects. And manager or helper classes that do everything and grow forever.

Avoid these
  • patterns for their own sake
  • a static singleton driver
  • builders with no defaults
  • facades that assert
  • deep inheritance instead of composition
  • "manager" classes that do everything

Say it like this

In the interview, name patterns with the problem each solved. Page objects with a fluent style. A driver factory driven by configuration for browsers and the grid. Builders for test data with defaults. A facade for the checkout flow. A strategy for UI or API login. A decorator listener for logging and screenshots. And explain one you avoided: no static singleton driver, one driver per test, so the suite runs in parallel.

In the interview
  • "Page objects with a fluent
  • style; a driver factory driven
  • by config; builders for test
  • data with defaults; a facade
  • for checkout; a strategy for UI vs API login; a decorator
  • listener for logging and screenshots. No static
  • singleton driver: one per test, so it runs in parallel."

Interview questions

Q1Which design patterns are common in test automation?

Page object (often fluent), factory (drivers), builder (test data), facade (flows), strategy (login, environments), decorator/listener (logging, screenshots), and sometimes singleton (config) and screenplay.

Q2Why use a builder for test data?

It gives readable, intention-revealing setup with defaults, so tests set only relevant fields and do not break when new fields are added.

Q3Why is a singleton WebDriver a problem?

Shared state leaks between tests and parallel runs collide; use a driver per test (or ThreadLocal) created by a factory.

Q4What is a driver factory?

A factory that builds the configured WebDriver (browser, options, local or remote) so creation logic lives in one place.

Q5What is the strategy pattern, in a test framework?

Interchangeable implementations behind one interface, chosen by config, such as UI login versus API login.

Q6How does Selenium support the decorator pattern?

EventFiringDecorator wraps a WebDriver with a WebDriverListener to run code before and after actions, for logging or evidence.

Q7What is the screenplay pattern?

A user-centred model where actors with abilities perform tasks and ask questions; it scales for large suites (for example Serenity BDD).

Q8How do SOLID principles apply to test code?

Small single-purpose classes, extension without editing tests, substitutable implementations, small interfaces, and tests depending on abstractions.