QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Assertions and API tests

REST Assured, the Builder for data and Lombok

REST Assured removes HTTP noise in a BDD style: given() describes the request, when() executes it and then() checks the response. Shared settings go into a RequestSpecification, and a Builder supplies valid defaults so a test changes only the field it cares about, while unique values (an email) keep parallel tests independent. Lombok generates code at compile time, but a record is often enough for simple data.

Java · Assertions and API

An API test is thirty lines of setup and one line of checking. How do you cut the noise?

A good API test reads like a story: "under these conditions this action gives this result". The three tools of this lesson help: REST Assured removes HTTP noise, a Builder prepares data, and Lombok saves class boilerplate. The lesson explains when each one is justified.

How it works and why. REST Assured is a BDD-style DSL. The chain reads top to bottom: given() describes the request, when() executes it, then() checks the response. The response body can be checked through a path in GPath notation and Hamcrest matchers, or deserialised into a POJO and checked with AssertJ.

Three parts of a request

given()URL, headers, body, authwhen()get / post / put / deletethen()status, headers, body, schema
Figure 1. Conditions, action and checks are separate, so the test shows what exactly changes the result.

Example: creating a user. Shared settings (URL, content type, authorisation) go into a RequestSpecification instead of being repeated in every test:

RequestSpecification requestSpec = new RequestSpecBuilder()
    .setBaseUri(System.getProperty("base.url", "https://api.example.test"))
    .setContentType(ContentType.JSON)
    .addHeader("Authorization", "Bearer " + token)
    .build();

// once per class: details only on failure
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
User created = given()
    .spec(requestSpec)
    .body(newUser)                      // POJO → JSON
.when()
    .post("/users")
.then()
    .statusCode(201)
    .header("Location", containsString("/users/"))
    .body("id", notNullValue())
    .extract().as(User.class);          // JSON → POJO

assertThat(created.name()).isEqualTo(newUser.name());

Serialising an object to JSON needs a library on the classpath (Jackson, Gson or JSON-B); without it the call with body(newUser) fails. To see the request and response only on failure, use enableLoggingOfRequestAndResponseIfValidationFails() or log().ifValidationFails() in a single test: the CI log is not cluttered by successful calls. A single value is taken with extract().path("id"). Schema validation is a separate json-schema-validator module with the matchesJsonSchemaInClasspath matcher.

A Builder for test data. A constructor with ten parameters is unreadable, and tests need different variants of one object. A Builder sets valid defaults, and the test changes only the field that matters for the scenario.

Constructor and Builder

Constructor

new User(null, "a", null, true, 0, …)

Ten positions: unclear which field is the negative case and which is filled just to compile.

Builder

aUser().withEmail(null).build()

Valid defaults, and the test names only the field that matters for the scenario.

Figure 2. The reader of the test sees at once which field is special: only it is named.
public final class UserBuilder {
    private String email = "qa+" + UUID.randomUUID() + "@example.test"; // unique
    private String name = "Anna";
    private Role role = Role.USER;

    public static UserBuilder aUser() { return new UserBuilder(); }
    public UserBuilder withEmail(String e) { this.email = e; return this; }
    public UserBuilder withRole(Role r) { this.role = r; return this; }
    public User build() { return new User(email, name, role); }
}

User admin = aUser().withRole(Role.ADMIN).build();
User noEmail = aUser().withEmail(null).build();   // negative case

Unique values (an email with a UUID, a random login) are generated right in the builder: then parallel tests do not fight over one account. Defaults must be valid for the server, otherwise any test that changes one field would fail for a different reason.

Lombok generates code at compile time through annotation processing. For test data these are useful: @Builder (with @Builder.Default for defaults), @Value (an immutable class) and @Jacksonized (so Jackson creates the object through the builder). For logging there is @Slf4j.

@Value
@Builder(toBuilder = true)
@Jacksonized                         // Jackson builds the object through the builder
public class UserDto {
    @Builder.Default String name = "Anna";
    @Builder.Default Role role = Role.USER;
    String email;
}

UserDto admin = UserDto.builder().role(Role.ADMIN).build();

Lombok is added as a dependency with scope provided, and an IDE plugin is needed so the editor sees the generated methods. In Maven it is wise to declare the processor explicitly: since JDK 23 annotation processors from the classpath do not run by default, and without the entry the build will not find the generated methods.

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <annotationProcessorPaths>
      <path>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
      </path>
    </annotationProcessorPaths>
  </configuration>
</plugin>

Limits and alternatives.

  • The modern alternative to Lombok for simple data is a record: immutable, with ready equals, hashCode and toString, no plugin at all. A builder for a record is written by hand, as above, or the constructor stays if there are few fields.
  • Be careful with @Data on mutable classes: it generates equals and hashCode over all fields, and an object in a HashSet gets "lost" after a field changes.
  • Lombok hides code the reader does not see. If the team decides not to use it, nothing is lost: records and a hand-written builder cover the same cases.
  • REST Assured does not replace contract tests. To check structure, a schema is better than ten body(...) calls, one per field.
  • Do not mix check logic with setup: a separate client or a createUser(user) method makes the test shorter and gives one place for changes.

Typical mistakes.

  • Repeating baseUri, headers and the token in every test instead of a RequestSpecification.
  • Turning on log().all() everywhere: the CI log is clogged and the real failure drowns.
  • A builder with unusable defaults: every test has to override them.
  • A static email in the builder in a parallel run: tests fight over one user.
  • Making ten body(...) checks instead of one deserialised object with AssertJ or a schema.

Check yourself

Why is it better to keep shared request settings in a RequestSpecification?

Answer

Base URI, content type and authorisation are set once and attached through spec(...). There is one place to change, and the test shows only the details that matter to it.

What role do defaults play in a data Builder?

Answer

They are valid, so a test can change one field and check exactly that. Unique values (an email) in them make parallel tests independent.

Why can a Lombok build fail on JDK 23 though it worked on JDK 21?

Answer

Since JDK 23 annotation processors from the classpath do not run by default. The Lombok processor must be declared explicitly in the compiler annotationProcessorPaths.

In the interview. Junior: REST Assured builds a request in the given, when, then shape: conditions, action, checks. I move shared setup into a RequestSpecification and check the response with matchers or deserialise it into a POJO. A Builder gives valid defaults, and the test changes only the needed field. Middle/Senior: I enable logging only on failure, generate unique values in the builder for parallel runs and check the response structure with a schema. I take Lombok for builders and immutable data, but prefer a record for simple data. I know about annotation processors in JDK 23 and declare them explicitly in Maven.

More articles in this chapter