The “given / expect / when” syntax and the “given / when / then” syntax in RestAssured serve similar purposes but have notable differences in structure and functionality.
“given / expect / when” Syntax
- Legacy Approach: This syntax was the standard in earlier versions of RestAssured (1.x). It allows you to set up your request and expectations in a single chain.
- Multiple Assertions: One of the key benefits is that it lets you define all your expectations before the request is made. This means if there are multiple assertion failures, they can all be reported at once, which is useful for debugging.
- Example:
given()
.param("x", "y")
.expect()
.statusCode(400)
.body("lotto.lottoId", equalTo(6))
.when()
.get("/lotto");
“given / when / then” Syntax
- Recommended Approach: This syntax became the preferred method starting from RestAssured 2.0 due to its alignment with Behavior Driven Development (BDD) practices. It separates the setup, action, and verification phases more clearly.
- Single Assertion Reporting: In this approach, if multiple assertions are made, only the first failure will be reported. This means you might need to run the test multiple times to catch all errors.
- Example:
given()
.param("x", "y")
.when()
.get("/lotto")
.then()
.statusCode(400)
.body("lotto.lottoId", equalTo(6));
Summary of Differences
- Error Reporting: “given / expect / when” reports all assertion failures at once, while “given / when / then” reports only the first failure.
- Clarity and Readability: The “given / when / then” syntax is generally considered more readable and aligns better with BDD principles.
- Usage Context: The “given / expect / when” syntax is still functional but is seen as legacy, while “given / when / then” is the recommended practice for new tests.
In conclusion, while both syntaxes can be used effectively, the “given / when / then” approach is favored for its clarity and alignment with modern testing practices.