Notes
Setup
Add REST Assured to the Maven project you built in lab four, with test scope, next to JUnit five, and add Jackson for turning JSON into Java objects. Pin the version, here five point five point zero. In test classes, import REST Assured's static methods and Hamcrest's matchers, so you can write given, when and then without a class name in front of every call.
<dependency> <groupId>io.rest-assured </groupId> <artifactId>rest-assured </artifactId> <version>5.5.0</version> <scope>test</scope> </dependency> + junit-jupiter, jackson-databind import static io.restassured .RestAssured.*;
given / when / then
Every REST Assured test has the same shape. Given sets up the request: the base address, headers, body. When makes the call: get product one. Then checks the response: status two hundred, sku BK one oh one, price twelve hundred and fifty cents. The body checks use JSON paths, like sku or items dot size, and Hamcrest matchers, like equal to. If a check fails, the message shows the expected and actual value and the path.
@Test void productOne() {
given()
.baseUri("http://localhost:8080")
.when()
.get("/api/products/1")
.then()
.statusCode(200)
.body("sku", equalTo("BK-101"))
.body("priceCents",
equalTo(1250));
} Specifications
Repeating the base address in every test is a maintenance trap. Build a request specification once: base URL read from a system property with localhost as the default, content type JSON, and some logging. Every test starts with given spec shop. Point the whole suite at staging by passing dash D base URL on the Maven command line. A response specification does the same for shared checks, like content type.
static RequestSpecification shop =
new RequestSpecBuilder()
.setBaseUri(System.getProperty(
"baseUrl",
"http://localhost:8080"))
.setContentType(ContentType.JSON)
.log(LogDetail.URI)
.build();
given().spec(shop)...
-DbaseUrl=https://staging... Extract a token
Most tests need a logged in user. A helper posts the email and password to the login endpoint, checks two hundred, and extracts the token with a JSON path. A map becomes the JSON body automatically. Later requests add the token with auth dot oauth two, which sends a bearer header, or with an explicit authorization header. Logging in through the API takes milliseconds, so each test can use its own user.
static String tokenFor(String email,
String pw) {
return given().spec(shop)
.body(Map.of("email", email,
"password", pw))
.when().post("/api/auth/login")
.then().statusCode(200)
.extract().path("token");
}
// .auth().oauth2(token) or
// .header("Authorization", ...) The coupon test
Now the real test for rule price three. Log in as Alice. Add four notebooks, which is exactly fifty dollars. Apply save ten in lower case, because codes are not case sensitive. Then expect two hundred, a discount of five hundred cents, and a total of forty nine ninety nine, which includes four ninety nine shipping. Reset the data before each test. Switch on the coupon boundary bug and this test fails with a clear message about the coupon.
String t = tokenFor(ALICE, PW);
given().spec(shop).auth().oauth2(t)
.body(Map.of("productId", 1,
"quantity", 4))
.post("/api/cart/items");
given().spec(shop).auth().oauth2(t)
.body(Map.of("code", "save10"))
.when().post("/api/cart/coupon")
.then().statusCode(200)
.body("discountCents", is(500))
.body("total", is("$49.99")); Matchers and paths
JSON paths and Hamcrest matchers cover most needs. Items dot size checks a list's length. Items, index zero, dot sku reads one element, and items dot sku with has items checks values across the whole list. Nested fields use dots, like coupon dot applied. For errors, check the error code field. Time with less than checks response time, and header checks headers. Many small precise checks beat one giant string comparison.
.body("items.size()", is(1))
.body("items[0].sku",
equalTo("BK-101"))
.body("items.sku",
hasItems("BK-101"))
.body("coupon.applied", is(true))
.body("error",
equalTo("invalid_quantity"))
.time(lessThan(500L))
.header("Content-Type",
containsString("json")) POJOs
For bigger responses, map the JSON to Java objects, often called POJOs; records work nicely. A cart record holds a list of line records and a total. Extract as Cart dot class, and Jackson fills it in. Now assertions are typed: the IDE completes field names and the compiler catches typos. Configure Jackson to ignore unknown fields, so an API adding a new field does not break every test. Use the same idea for request bodies.
record Line(long productId,
String sku, int quantity,
long lineCents) {}
record Cart(List<Line> items,
long totalCents) {}
Cart cart = given().spec(shop)...
.get("/api/cart")
.then().statusCode(200)
.extract().as(Cart.class);
assertEquals(4999, cart.totalCents()); Logging
When an API test fails in CI, you need the request and the response. Logging everything for every test drowns the output. Turn on REST Assured's logging only if validation fails: a failing test then prints the method, address, headers and both bodies, and passing tests stay quiet. Mask tokens before reports are shared. In Part seven, Allure attaches these to a readable report.
RestAssured .enableLoggingOfRequestAnd ResponseIfValidationFails(); failure output then shows: method, URI, headers, body status, response body mask tokens in shared reports Allure can attach them (Part 7)
Common mistakes
REST Assured habits to avoid. Hard coded base URLs in every test. Getting tokens through the UI. One long test that makes ten calls and checks only the last. Checking only the status code. Comparing the whole JSON response as one string, which breaks on any harmless change like a new field. One shared user for every test. And logging everything always, which hides the one failure you are looking for.
- hard-coded base URLs
- logging in through the UI
- one test doing 10 calls and checking only the last
- checking only statusCode
- asserting the whole JSON string (breaks on any change)
- shared user across tests
- log().all() everywhere
Say it like this
In the interview: JUnit five tests with a shared request specification, base URL from configuration, JSON content type, and logging only on failure. A helper gets tokens through the login API. Tests follow given, when, then, and check the status plus specific JSON paths or typed POJOs, never just the status. Each test resets or creates its own data, and the suite runs in CI against any environment by changing one property.
- "JUnit 5 tests with a shared
- request spec: base URL from config, JSON, and logging on failure. A helper gets tokens
- via the login API. Tests use
- given/when/then, check status
- and specific JSON paths or POJOs, reset or create their own data, and run in CI
- against any environment."