skip to content

In Catch2, how do SCENARIO, GIVEN, WHEN and THEN map onto TEST_CASE and SECTION, and where does AND_WHEN go?

level: middleimportance: should knowfreq 30%

answer

  1. aliases, not a new engine
  2. Scenario: prefix on the name
  3. clauses are sections
  4. AND_ goes inside its parent

basics

~20 s

SCENARIO is a TEST_CASE whose name gains a "Scenario: " prefix, and GIVEN, WHEN and THEN are sections with prefixed names. AND_GIVEN, AND_WHEN and AND_THEN go inside the clause they depend on; Catch2 enforces no ordering.

solid answer

~40 s

Catch2's BDD macros are thin aliases. `SCENARIO(name, tags)` expands to `TEST_CASE` with `"Scenario: "` glued to the front of the name, so a name filter must include that prefix. `GIVEN`, `WHEN` and `THEN` each open a section whose name carries a `Given:`, `When:` or `Then:` label, and the console reporter aligns those labels in its output. Because they are sections, the re-entry model applies unchanged: a `GIVEN` holding two independent `WHEN` clauses runs once for each leaf beneath it, so each `WHEN` starts from fresh givens. A clause that must happen after another, rather than beside it, is written with `AND_GIVEN`, `AND_WHEN` or `AND_THEN` nested inside the clause it depends on. Nothing checks that a `THEN` follows a `WHEN`; the ordering is the author's discipline.

code

cpp · 23 lines
cpp
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <stack>

SCENARIO("a stack can be pushed and popped", "[stack][bdd]") {
    GIVEN("a stack with three items") {
        std::stack<int> s;
        s.push(1); s.push(2); s.push(3);
        std::cout << "given runs\n";
        WHEN("one item is popped") {
            s.pop();
            THEN("two remain") { REQUIRE(s.size() == 2u); }
            AND_WHEN("another is popped") {
                s.pop();
                THEN("one remains") { REQUIRE(s.size() == 1u); }
            }
        }
        WHEN("an item is pushed") {
            s.push(4);
            THEN("the top is the new item") { REQUIRE(s.top() == 4); }
        }
    }
}

go deeper

for a junior

Recall that SCENARIO is a test case and GIVEN, WHEN and THEN are sections with labelled names, and recognise the prefixed names in a report.

for a middle

Explain independent versus dependent clauses, place AND_WHEN correctly, and count how many times a GIVEN body runs for a given tree of clauses.

for a senior

Review BDD-style tests for hidden coupling: setup in a GIVEN multiplied by its leaves, dependent steps written as siblings, and filters that forget the Scenario prefix.

for a principal

Decide whether the BDD spelling earns its place in a codebase, weighing report readability for non-authors against a second vocabulary for the same mechanism.

## Aliases over the same engine Catch2 offers a second spelling for tests that read like executable specifications. The macros add no runtime of their own: the Catch2 3.16.1 source defines them in `catch_test_macros.hpp` as one-line wrappers. - `SCENARIO(name, tags)` is `TEST_CASE("Scenario: " name, tags)`. The name is a string literal concatenated with the prefix. - `SCENARIO_METHOD(fixture, name, tags)` is the same for a fixture-based case. - `GIVEN(desc)`, `WHEN(desc)` and `THEN(desc)` are sections. In the source each one is a **dynamic section** whose name is the description with a padded label in front: `Given:`, `When:` or `Then:`. - `AND_GIVEN`, `AND_WHEN` and `AND_THEN` are sections labelled `And given:`, `And when:` and `And:`. Everything known about sections therefore holds: each leaf clause gets its own run of the scenario from the top. ## Independent and dependent clauses The documentation separates two relationships: 1. **Independent** clauses are siblings. A `GIVEN` may hold several `WHEN` clauses that each use the same starting objects in different ways. Because each is a leaf path, each starts from freshly constructed givens. 2. **Dependent** clauses happen after another clause has run and been checked. They use an `AND_` macro placed **inside** the clause they depend on. Several independent `AND_` clauses can depend on one outer clause. Placing an `AND_WHEN` beside the `WHEN` instead of inside it does not make it dependent; it simply becomes one more independent sibling that never sees the first `WHEN`'s effect. ## A stack scenario ```cpp SCENARIO("a stack can be pushed and popped", "[stack][bdd]") { GIVEN("a stack with three items") { std::stack<int> s; s.push(1); s.push(2); s.push(3); WHEN("one item is popped") { s.pop(); THEN("two remain") { REQUIRE(s.size() == 2u); } AND_WHEN("another is popped") { s.pop(); THEN("one remains") { REQUIRE(s.size() == 1u); } } } WHEN("an item is pushed") { s.push(4); THEN("the top is the new item") { REQUIRE(s.top() == 4); } } } } ``` The leaves are the three `THEN` clauses, so the scenario runs three times: | Run | Path | |---|---| | 1 | given three items, when one is popped, then two remain | | 2 | given three items, when one is popped, and when another is popped, then one remains | | 3 | given three items, when an item is pushed, then the top is the new item | The `GIVEN` body builds the stack three times, and the first `WHEN` pops twice in total, once for each leaf beneath it. Run 2 sees the first pop because its `AND_WHEN` is nested inside that `WHEN`. ## Names, reports and filters - The registered test name includes the prefix, so `--list-tests` shows `Scenario: a stack can be pushed and popped`. A filter on the bare text `a stack can be pushed and popped` matches nothing; the full prefixed name or a wildcard does. - The console reporter recognises the labels and aligns the givens, whens and thens in a failure header, which is most of the readability gain. - Since the clauses are dynamic sections, a description can be streamed, as in `WHEN("popping " << n << " items")`, which helps when the clause sits inside a loop. ## What the macros do not do - They do not enforce order. A `THEN` with no `WHEN`, or a `WHEN` inside a `THEN`, compiles and runs; the documentation says plainly that sequencing is the programmer's responsibility. - They do not change failure handling or add steps to a report beyond the prefixed names. - They are not a process. Whether a team writes specifications with stakeholders is a separate decision; in code, these are sections with better names. - They do not make clause descriptions unique for you. Two `THEN("it works")` clauses under the same `WHEN` produce two indistinguishable lines in a report, so descriptions should state the expected outcome. ## When the spelling earns its place - Behaviour with a clear precondition, action and outcome, such as a container's state transitions, reads naturally. - Tests reviewed by people who read the report more than the code benefit from the aligned labels. - For a small algorithm with one input and one check, a plain `TEST_CASE` is shorter and says the same.

  • Why does a Catch2 name filter on a SCENARIO's text alone match nothing?
    `SCENARIO` concatenates `"Scenario: "` onto the name at compile time, so the registered name is `Scenario: a stack can be pushed and popped`. A name filter must match that full string, or use a wildcard such as `*pushed and popped`. Tags are unaffected, so tagging scenarios is the more robust way to select them.
  • In Catch2, how many times does a GIVEN body run when it holds two WHEN clauses, each with two THEN clauses?
    Four times. The four `THEN` clauses are the leaves, and Catch2 re-runs the scenario once per leaf, entering the `GIVEN` each time. Each `WHEN` body runs twice, once for each `THEN` beneath it.

  • Catch2's GIVEN runs once and its WHEN clauses run in sequence on that state.
  • An AND_WHEN placed beside a WHEN runs after it on the same state.
  • Catch2 rejects a THEN that is not inside a WHEN.
  • SCENARIO registers the test under exactly the name you wrote.
  • The BDD macros are a separate test engine from TEST_CASE and SECTION.