Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Hooks, Tags, UI Tests and Suite Health

Practice what you learned about Cucumber hooks, tags, page objects, reports, CI and scenario quality: ten exercises with solutions, runnable checks and a review cheat sheet.

You have covered hooks and tags, state and test data, page objects and UI tests, reports and CI, and the patterns and pitfalls that decide whether a suite survives. This final lesson of the slice turns that knowledge into practice: ten exercises with solutions, two runnable checks you can adapt, and a one-page review sheet to keep next to your editor.

Cucumber cannot run on this site, so most exercises are written and reviewed on paper, and the runnable parts are small Java stand-ins. Try each exercise before opening its solution.

Exercises

1. Predict the hook order

A project has these hooks. List the exact output for one scenario that has the tag @web and a single step.

Java
@Before(order = 5)            public void a() { print("A"); }
@Before(value = "@web", order = 1)  public void b() { print("B"); }
@Before(value = "@api", order = 2)  public void c() { print("C"); }
@After(order = 1)             public void d() { print("D"); }
@After(order = 9)             public void e() { print("E"); }
Solution

Before hooks ascending: B (order 1, tag matches), A (order 5). C is skipped because the scenario is not @api. Then the step. After hooks descending: E (9), then D (1). Output: B, A, step, E, D.

Check your answer with the stand-in below.

Java Check exercise 1 (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

2. Write the tag expressions

Write one expression for each need: (a) smoke scenarios that are not work in progress; (b) everything in checkout or payments except slow ones; (c) scenarios that need neither a browser nor a database.

Solution

(a) @smoke and not @wip. (b) (@checkout or @payments) and not @slow. (c) not @web and not @db. Use parentheses when mixing or with and.

3. Fix the shared state

A team keeps private static Customer customer; in CustomerSteps and reads it in OrderSteps. Parallel runs fail randomly. Describe the fix.

Solution

Create a plain class ShopWorld with a customer field, let the DI container (PicoContainer or Spring with @ScenarioScope) inject it into both step classes through their constructors, and delete the static field. Each scenario then gets its own world.

4. Make the data independent

Two scenarios create the user [email protected]; the second fails with "email already exists". Give two different fixes.

Solution

Generate a unique email per scenario in a builder (for example with a counter or UUID suffix) and keep "Alice" as the display name in the world; or roll back or delete created data in @After (and clear before the scenario) so the address is free again. The first fix also works in parallel.

5. Design a page object

Sketch the public methods of a CheckoutPage that fills an address, selects a payment method, submits and returns a confirmation page.

Solution
Java
public class CheckoutPage {
    public CheckoutPage enterAddress(Address address) { /* fill fields */ return this; }
    public CheckoutPage choosePayment(PaymentMethod method) { /* select */ return this; }
    public ConfirmationPage placeOrder() { /* click, wait */ return new ConfirmationPage(driver); }
    public String validationMessage() { /* text of the error banner */ }
}

Methods express intentions, return the next page object, contain no assertions, and keep locators private.

6. Replace the sleep

A step contains Thread.sleep(3000) before clicking "Pay". Rewrite it.

Solution

Inside the page object use an explicit wait: new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(payButton)).click();. The step calls checkout.pay() and contains no timing.

7. Choose the level

For each behavior choose service, API or UI level: (a) VAT is calculated per country; (b) the API returns 401 without a token; (c) the cart icon shows a red badge when the cart is not empty and can be reached by keyboard.

Solution

(a) service layer, a pure rule. (b) API level, since the contract is the product. (c) UI level, because the behavior exists only in the browser.

8. Rewrite declaratively

Rewrite: "When I click Add to cart, And I click the cart icon, And I click Checkout, And I type 4242... into the card field, And I click Pay".

Solution

When she buys the book with her credit card, preceded by Given the catalog has the book "Learning SQL" if the title matters. Everything else belongs to step definitions and page objects.

9. Diagnose the flake

A scenario fails once in ten runs when alone, always passes in the morning and fails more often on the loaded CI machine. What do you suspect first, and what do you change?

Solution

Timing: it behaves differently under load and fails alone, so it is not data collision. Replace fixed sleeps with explicit waits for the exact condition, attach a screenshot and page source on failure, then repeat the run 50 times to prove the fix. Do not add blind retries.

10. Plan the pipeline

Design stages for a suite with 40 smoke, 400 regression and 30 slow cross-browser scenarios.

Solution

Pull requests: @smoke and not @wip (about 40, minutes, headless). After merge: not @wip and not @slow-nightly, parallel across threads or shards. Nightly: everything including cross-browser. Always upload JUnit XML, the HTML report and screenshots with if: always(), and quarantine flaky scenarios with a visible tag.

A readiness check you can adapt

Before a feature file is merged, run a checklist. This stand-in scores a draft with the review rules from the patterns chapter. Edit the draft and watch the score change.

Java Feature review score (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

One-page review sheet

Topic Remember
Hooks Before ascending, After descending; After always runs; BeforeAll and AfterAll are static (hooks)
Tags inherited downward; and, or, not; pass with cucumber.filter.tags (tags)
State one injected object per scenario; no static fields (state)
Data visible when it affects the outcome; unique values; clean before and after (data)
UI page objects, component objects, explicit waits, stable locators (page objects, waits)
Levels lowest level that proves the behavior (levels)
Reports and CI JUnit XML, HTML, screenshots, if: always(), staged tags (reports, CI)
Speed and flakes parallel, isolate, shortcut login, quarantine (flaky)
Quality declarative, one behavior, no anti-patterns (declarative, anti-patterns)
Collaboration three amigos, example mapping, living docs (collaboration)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. For a scenario tagged @web, which sequence is right for @Before(order=1, @web), @Before(order=5), @After(order=1), @After(order=9)?

    Before hooks run ascending and After hooks descending.
  2. 2. Which expression selects smoke scenarios that are not work in progress?

    Both conditions must hold, so use and, with not applied to @wip.
  3. 3. A UI scenario flakes on a loaded CI machine but passes locally. What is the best first improvement?

    Timing problems are fixed by waiting for the real condition, not by longer sleeps or hiding retries.
  4. 4. Which behavior is best tested at the UI level?

    Focus order exists only in the browser; the others are business rules better tested below the UI.

Summary

  • Practice predicting hook order, writing tag expressions and fixing shared state and data.
  • Put waits and locators in page objects, choose the lowest effective test level and keep scenarios declarative.
  • Run staged, parallel pipelines that always keep reports, and treat flakes as bugs.
  • Keep the review sheet handy and revisit the chapters when a suite starts to hurt.

Next: Back to the Cucumber and BDD track