Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Page Objects and UI Tests

API and Service-Layer Scenarios

Test business rules below the UI with Cucumber: service-layer scenarios, REST API steps with an HTTP client, sharing the last response, and choosing the right level of test.

Many teams meet Cucumber through browser tests, then conclude that BDD is slow and brittle. The problem is the level, not the tool. Cucumber scenarios can drive any layer: the browser, an HTTP API, or plain Java objects in the same process. A rule like "gold customers get free shipping" does not need a browser at all. Testing it through the UI costs seconds and invites flakiness; testing it through the service layer costs milliseconds and fails only for real reasons.

This lesson shows how to point the same Gherkin at lower levels, how to write REST steps, and how to decide where each scenario belongs. Real REST libraries and a server for your application are not available here, so the library code is read-only, while the runnable examples use Java's built-in HTTP server and client on the loopback interface, plus a service-layer stand-in.

flowchart TB
    A["UI scenarios<br/>few, slow"] --> B["API scenarios<br/>some, medium"]
    B --> C["Service-layer scenarios<br/>many, fast"]
    style C fill:#d1fae5,stroke:#059669

The lower the level that can express the behavior, the cheaper and more stable the scenario.

Same scenario, different glue

Take one scenario:

GHERKIN
Scenario: Gold customers ship free
  Given a customer "Mina" with a gold membership
  And a cart worth 20 dollars
  When she checks out
  Then shipping costs 0 dollars

The Gherkin says nothing about how checkout is triggered. Three step definition sets can serve it:

  • UI glue fills forms through page objects (page objects).
  • API glue sends POST /checkout and parses the JSON.
  • Service glue calls checkoutService.checkout(customer, cart) directly.

Switching glue changes speed, not the scenario. You can even keep two glue packages and choose with a configuration parameter, running the same feature files at two levels.

Service-layer steps

Calling the code under test directly is the fastest option. The steps create real domain objects (often with in-memory repositories) and call real services:

Java
public class ShippingSteps {
    private final ShopWorld world;
    private final CheckoutService checkout = new CheckoutService(new InMemoryRates());

    public ShippingSteps(ShopWorld world) { this.world = world; }

    @Given("a cart worth {int} dollars")
    public void cart(int amount) {
        world.cart = Cart.worth(Money.dollars(amount));
    }

    @When("she checks out")
    public void checkout() {
        world.receipt = checkout.checkout(world.customer, world.cart);
    }

    @Then("shipping costs {int} dollars")
    public void shipping(int expected) {
        assertEquals(Money.dollars(expected), world.receipt.shipping());
    }
}

Here is the idea running, with a compact CheckoutService.

Java Service-layer scenario steps (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.

(These stand-ins use static fields only because a single main has no container; in real glue use an injected world, see Scenario state.)

REST API steps

When the behavior lives in an HTTP contract, drive the real endpoint. Java developers often use REST Assured, the JDK's HttpClient, or Spring's TestRestTemplate. A typical step set remembers the last response in the world, so assertion steps can inspect it:

Java
public class ApiSteps {
    private final ApiWorld world;

    public ApiSteps(ApiWorld world) { this.world = world; }

    @Given("the API is running")
    public void running() {
        RestAssured.baseURI = System.getProperty("api.url", "http://localhost:8080");
    }

    @When("I request the product with id {int}")
    public void get(int id) {
        world.response = RestAssured.given().accept("application/json")
                .when().get("/products/" + id);
    }

    @When("I create a product named {string} priced {int}")
    public void create(String name, int price) {
        world.response = RestAssured.given()
                .contentType("application/json")
                .body(Map.of("name", name, "price", price))
                .when().post("/products");
    }

    @Then("the status code is {int}")
    public void status(int code) {
        assertEquals(code, world.response.statusCode());
    }

    @Then("the JSON field {string} is {string}")
    public void field(String path, String value) {
        assertEquals(value, world.response.jsonPath().getString(path));
    }
}
GHERKIN
Scenario: Create and read a product
  When I create a product named "Pen" priced 3
  Then the status code is 201
  When I request the product with id 1
  Then the JSON field "name" is "Pen"

Keep API scenarios about behavior and contract: status codes, key fields, error messages, security rules. Do not paste whole JSON documents into Gherkin; compare the few fields that matter.

The runnable example below starts a tiny HTTP server inside the program, calls it with Java's HttpClient and checks the last response, exactly the "last response in the world" pattern.

Java REST steps against a local server (Java)

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.

Choosing the level

Question Lean toward
Is it a business rule (prices, eligibility, limits)? service layer
Is the contract the product (public API, status codes, auth)? API level
Does the behavior only exist in the browser (layout, JavaScript, accessibility)? UI level
Is it a complete journey that proves the parts are wired together? a handful of UI or API smoke scenarios

Aim for a pyramid: many fast scenarios at the bottom, few slow ones on top. Teams that invert it, with hundreds of UI scenarios, suffer slow builds and flaky pipelines; see Flaky and slow suites.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about the same Gherkin and different glue code is true?

    Gherkin describes behavior. How the steps are executed is decided by the glue code.
  2. 2. Why store the last response in a shared object?

    A When step performs the request, and Then steps assert on it, so the response must be shared within the scenario.
  3. 3. A free-shipping rule for gold customers is best tested at which level?

    It is a business rule that does not need a browser or HTTP, so a fast service-level scenario is cheapest and most stable.
  4. 4. What should API scenarios avoid?

    Big payloads in Gherkin hide the point and break on irrelevant changes.

Summary

  • Cucumber can drive the UI, an HTTP API or in-process services; the Gherkin stays the same.
  • Service-layer glue is fastest; API glue tests the contract; UI glue is for what needs a browser.
  • Remember the last response in the scenario's world and assert on a few meaningful fields.
  • Build a test pyramid: many fast scenarios, few slow ones.

Next: Reports and plugins