π Boilerplate Elimination, Fluent Construction & Immutable Mutation
In comprehensive API automation suites, authoring dozens of negative tests, boundary edge scenarios, and field-permutation checks creates significant test maintenance friction when relying on telescoping constructors or verbose setter chains. Modifying a 20-field POJO across hundreds of tests often breaks constructor signatures and exposes mutable state across parallel test threads. Project Lombok's @Builder pattern revolutionizes dynamic payload generation in REST Assured by implementing the GoF Builder Pattern during compilation via AST (Abstract Syntax Tree) transformation. By coupling @Builder with toBuilder = true, @Singular for fluent collection addition, @Builder.Default for canonical baseline state, and Jackson's @Jacksonized annotation, automation architects synthesize valid baseline payloads and create targeted field variations in a single, expressive method call.
LOMBOK COMPILE-TIME ANNOTATION PROCESSING & SERIALIZATION PIPELINE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SOURCE CODE (src/test/java) β
β @Getter @Builder(toBuilder = true) @Jacksonized β
β public class StudentPayload { private String name; private int credits; } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Javac Annotation Processing Phase)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LOMBOK ANNOTATION PROCESSOR (lombok.launch.AnnotationProcessorHider$AnnotationProcessor) β
β βββ 1. Generates Public Getters: public String getName(), public int getCredits() β
β βββ 2. Generates All-Args Constructor: private StudentPayload(String name, int credits) β
β βββ 3. Synthesizes Static Factory: public static StudentPayloadBuilder builder() β
β βββ 4. Emits Fluent Inner Class: StudentPayloadBuilder with name(), credits(), build() β
β βββ 5. Generates Mutation Cloner: public StudentPayloadBuilder toBuilder() β
β βββ 6. Attaches @Jacksonized / @JsonPOJOBuilder for Jackson reflective deserialization β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Compiled Bytecode: target/test-classes)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β REST ASSURED EXECUTION RUNTIME β
β StudentPayload payload = StudentPayload.builder().name("Nikita").credits(16).build(); β
β given().contentType(ContentType.JSON).body(payload).when().post("/students")... β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Jackson Databind Ingestion)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIRE SERIALIZATION OUTPUT: {"name":"Nikita","credits":16} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
builder() pattern.
package com.nikita.restassured.models.lombok;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
@Getter
@ToString
@Builder
@Jacksonized // Ensures bidirectional compatibility with Jackson ObjectMapper
@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentRegistrationModel {
@JsonProperty("studentId")
private String studentId;
@JsonProperty("fullName")
private String fullName;
@JsonProperty("email")
private String email;
@JsonProperty("academicTrack")
private String academicTrack;
@JsonProperty("enrolledCredits")
private int enrolledCredits;
@JsonProperty("isActive")
private boolean active;
}
package com.nikita.restassured.lombok;
import com.nikita.restassured.models.lombok.StudentRegistrationModel;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class LombokPayloadExecutionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Synthesize request payload dynamically via fluent Lombok builder")
public void testCreateStudentWithLombokBuilder() {
// Fluent, readable instantiation without telescoping constructor confusion
StudentRegistrationModel payload = StudentRegistrationModel.builder()
.studentId("STU-88219")
.fullName("Nikita Sharma")
.email("nikita.sharma@nikita-infotech.com")
.academicTrack("ENTERPRISE_AUTOMATION")
.enrolledCredits(16)
.active(true)
.build();
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.header("X-Tenant-Key", "MAHARASHTRA_PUNE_01")
.body(payload)
.log().body()
.when()
.post("/students")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", equalTo("Nikita Sharma"))
.body("data.enrolledCredits", equalTo(16));
System.out.println("[β] Lombok @Builder payload successfully synthesized and serialized.");
}
}
toBuilder = true to clone a valid baseline model and selectively mutate single fields for negative boundary testing.
package com.nikita.restassured.lombok;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.restassured.http.ContentType;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.jackson.Jacksonized;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@Getter
@Builder(toBuilder = true) // Generates .toBuilder() cloner method
@Jacksonized
class CourseEnrollmentRequest {
@JsonProperty("studentId") private String studentId;
@JsonProperty("courseCode") private String courseCode;
@JsonProperty("credits") private int credits;
}
public class ToBuilderPermutationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
private CourseEnrollmentRequest baselineValidRequest;
@BeforeClass
public void setupValidBaseline() {
// Canonical valid baseline payload
baselineValidRequest = CourseEnrollmentRequest.builder()
.studentId("STU-88219")
.courseCode("REST-JAVA-201")
.credits(4)
.build();
}
@Test(description = "Negative Test: Mutate only credits to 0 to verify business validation")
public void testZeroCreditsBoundary() {
// Clone baseline and mutate single field without affecting other tests!
CourseEnrollmentRequest zeroCreditsPayload = baselineValidRequest.toBuilder()
.credits(0) // Negative boundary
.build();
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.body(zeroCreditsPayload)
.when()
.post("/courses/enroll")
.then()
.statusCode(422)
.body("detail", containsString("Credits must be between 1 and 6"));
System.out.println("[β] Verified 422 rejected payload with 0 credits.");
}
@Test(description = "Negative Test: Mutate only studentId to empty string")
public void testEmptyStudentIdBoundary() {
CourseEnrollmentRequest invalidIdPayload = baselineValidRequest.toBuilder()
.studentId("") // Negative edge
.build();
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.body(invalidIdPayload)
.when()
.post("/courses/enroll")
.then()
.statusCode(400)
.body("detail", containsString("studentId is required"));
System.out.println("[β] Verified 400 rejected payload with empty studentId.");
}
}
@Singular annotation to add items one-by-one to a List<T> without creating intermediary collection objects.
package com.nikita.restassured.models.lombok;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.Singular;
import lombok.extern.jackson.Jacksonized;
import java.util.List;
import java.util.Map;
@Getter
@Builder
@Jacksonized
public class BatchRegistrationPayload {
@JsonProperty("batchId")
private String batchId;
// @Singular creates: student(String s), students(Collection s), and clearStudents()
@Singular
@JsonProperty("students")
private List<String> students;
// @Singular on Maps creates: metadata(String key, Object value)
@Singular("metadataItem")
@JsonProperty("metadata")
private Map<String, Object> metadata;
}
// ==============================================================================
// USAGE IN TEST METHOD:
// ==============================================================================
// BatchRegistrationPayload payload = BatchRegistrationPayload.builder()
// .batchId("BATCH-PUNE-2026")
// .student("STU-88219") // Injects 1st student into list
// .student("STU-88220") // Injects 2nd student into list
// .student("STU-88221") // Injects 3rd student into list
// .metadataItem("campus", "Pune-West") // Injects single map entry
// .metadataItem("labRoom", "Lab-402") // Injects second map entry
// .build();
@Builder.Default prevents Lombok from overwriting initialized field defaults with Java null or zero values.
package com.nikita.restassured.models.lombok;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.jackson.Jacksonized;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.UUID;
@Getter
@Builder
@Jacksonized
class AssessmentSubmissionPayload {
@JsonProperty("submissionId")
@Builder.Default
private String submissionId = "SUB-" + UUID.randomUUID().toString().substring(0, 8);
@JsonProperty("studentId")
private String studentId;
@JsonProperty("scorePercentage")
@Builder.Default
private double scorePercentage = 100.0;
@JsonProperty("verified")
@Builder.Default
private boolean verified = true;
}
public class BuilderDefaultTest {
@Test(description = "Verify @Builder.Default retains initialized field values when omitted from builder")
public void testBuilderDefaultValues() {
// Intentionally provide ONLY studentId; all other fields must take their defaults:
AssessmentSubmissionPayload payload = AssessmentSubmissionPayload.builder()
.studentId("STU-88219")
.build();
System.out.println("[*] Generated Submission ID : " + payload.getSubmissionId());
System.out.println("[*] Default Score Percentage: " + payload.getScorePercentage());
System.out.println("[*] Default Verified Status : " + payload.isVerified());
// Assert defaults were retained rather than reset to null/0.0/false:
Assert.assertNotNull(payload.getSubmissionId());
Assert.assertTrue(payload.getSubmissionId().startsWith("SUB-"));
Assert.assertEquals(payload.getScorePercentage(), 100.0);
Assert.assertTrue(payload.isVerified());
}
}
package com.nikita.restassured.factories;
import com.nikita.restassured.models.lombok.StudentRegistrationModel;
import java.util.Random;
import java.util.UUID;
public class StudentDataFactory {
private static final Random RANDOM = new Random();
// Generates a fully populated, randomized, and valid default student payload
public static StudentRegistrationModel createDefaultStudent() {
String randomSuffix = UUID.randomUUID().toString().substring(0, 6);
return StudentRegistrationModel.builder()
.studentId("STU-" + (10000 + RANDOM.nextInt(90000)))
.fullName("TestUser_" + randomSuffix)
.email("student." + randomSuffix + "@nikita-infotech.com")
.academicTrack("ENTERPRISE_AUTOMATION")
.enrolledCredits(12 + (RANDOM.nextInt(3) * 2)) // 12, 14, or 16 credits
.active(true)
.build();
}
// Generates a specific honors student variation
public static StudentRegistrationModel createHonorsStudent() {
return createDefaultStudent().toBuilder()
.academicTrack("CLOUD_DEVOPS_QA")
.enrolledCredits(20)
.build();
}
// Generates a minimal boundary student
public static StudentRegistrationModel createMinimalStudent() {
return StudentRegistrationModel.builder()
.studentId("STU-" + (10000 + RANDOM.nextInt(90000)))
.fullName("Minimal Candidate")
.email("minimal." + UUID.randomUUID().toString().substring(0, 4) + "@domain.com")
.build();
}
}
package com.nikita.restassured.models.lombok;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.jackson.Jacksonized;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@Getter
@Builder
@Jacksonized
class Address {
@JsonProperty("city") private String city;
@JsonProperty("postalCode") private String postalCode;
}
@Getter
@Builder
@Jacksonized
class Contact {
@JsonProperty("phone") private String phone;
@JsonProperty("address") private Address address; // Nested POJO with Builder
}
@Getter
@Builder
@Jacksonized
class NestedStudentPayload {
@JsonProperty("id") private String id;
@JsonProperty("name") private String name;
@JsonProperty("contact") private Contact contact; // Nested POJO with Builder
}
public class NestedBuilderExecutionTest {
@Test(description = "Assemble 3-level nested object tree using chained builders")
public void testChainedNestedBuilders() {
NestedStudentPayload payload = NestedStudentPayload.builder()
.id("STU-88219")
.name("Nikita Sharma")
.contact(Contact.builder()
.phone("+91-9096808284")
.address(Address.builder()
.city("Pune")
.postalCode("411015")
.build())
.build())
.build();
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.contentType("application/json")
.body(payload)
.when()
.post("/students/nested")
.then()
.statusCode(201)
.body("data.contact.address.city", equalTo("Pune"))
.body("data.contact.phone", equalTo("+91-9096808284"));
System.out.println("[β] Nested builders chained and serialized cleanly.");
}
}
Cannot find symbol: method builder() in IntelliJ IDEA/Eclipse, and compiler plugin configurations.
MINTING LOMBOK ANNOTATION PROCESSOR IN MAVEN (pom.xml):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>17</source>
<target>17</target>
<annotationProcessorPaths>
<!-- Crucial: Hook Lombok into javac annotation processor chain -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
INTELLIJ IDEA & ECLIPSE CONFIGURATION CHECKLIST:
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β COMMON ERROR SYMPTOM β RESOLUTION PROCEDURE β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Cannot find symbol: β In IntelliJ: Go to Preferences βββΊ Build, Execution, Deployment β
β method builder() β βββΊ Compiler βββΊ Annotation Processors βββΊ Check "Enable annotation β
β β processing". β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β UnrecognizedPropertyEx β Add @Jacksonized to class so Jackson knows to use the builder β
β on deserialization β during unmarshalling: @Builder @Jacksonized β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Defaults reset to null β Ensure field has @Builder.Default when default values are assigned. β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PROJECT LOMBOK @BUILDER SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β ANNOTATION / ATTRIBUTE β TARGET PLACEMENT β GENERATED ARTIFACTβ PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β @Builder β Class Level β builder() method β Synthesizes fluent builder β
β toBuilder = true β @Builder(toBuilder = true) β .toBuilder() β Immutable mutation cloner β
β @Jacksonized β Class Level (with @Builder) β @JsonPOJOBuilder β Wires builder to Jackson read β
β @Singular β Collection / Map Field β item(), items() β Fluent 1-by-1 item addition β
β @Builder.Default β Initialized Field β Default Retainer β Preserves default field valuesβ
β @Getter β Class Level β getField() β Jackson serialization access β
β @ToString β Class Level β toString() β Detailed test failure logging β
β builderMethodName β @Builder(builderMethodName=..)Custom name β Renames static builder() β
β buildMethodName β @Builder(buildMethodName=..) β Custom name β Renames terminal .build() β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 LOMBOK @BUILDER BEST PRACTICES: β
β 1. Always pair @Builder with @Jacksonized: Ensures Jackson uses the builder for deserialization. β
β 2. Use toBuilder = true for negative testing: Clone a valid baseline and mutate single invalid fields. β
β 3. Annotate default fields with @Builder.Default: Prevent Lombok from resetting defaults to null. β
β 4. Leverage @Singular for collections: Populate lists and maps fluently without helper arrays. β
β 5. Create Test Data Factories with Builders: Centralize baseline generation across test classes. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ