Using Record Classes from Java in Test Automation
January 28, 2023
Introduction
Java 14 introduced Record classes which have very good inherent features. If we leverage this feature in automation we can simplify our code really well. Lets see a working example of record classes in java.
Application Under Test
Consider a todo api which has post endpoint /todo which accepts following json body
{
“title”:”<Some Title>”, // Mandatory
“status”: “<Todo Status>” // Optional either ACTIVE or DONE
}
Using Record Classes
In order for testing this endpoint with let’s say RestAssured we would need to send a body object. For post request. A request may look something like this.
public class TestCreationOfTodo {
@Test
public void shouldCreateTodoWithoutProvidingStatus(){
CreateTodoResponse response = given()
.baseUri("http://localhost:8080/v1")
.contentType(ContentType.JSON)
.body(new CreateTodoRequest("Bring Milk",null))
.when()
.post("/todo")
.then()
.statusCode(201)
.extract()
.body()
.as(CreateTodoResponse.class);
assertEquals(response.title(),"Bring Milk");
}
}
Here traditionally we may create plain classes like CreateTodoRequest CreateTodoResponse and write getters and setters for them or use some libraries like lombok to auto generate getters and setters. But What if I tell you that classes created above are record classes. And I haven’t used any library like lombok to generate getters. Although record classes don't provide setters ( since by default members of record classes are final ) yet it serves our purpose here, because we want request and response objects to be immutable once constructed. Below is code on how these classes look like.
public record CreateTodoRequest(String title,TodoStatus status) {
}
import java.util.Date;
public record CreateTodoResponse(String id,
String title,
TodoStatus status,
Date createdAt,
Date updatedAt) {
}
public enum TodoStatus {
ACTIVE,
DONE
}
Caution
Record classes feature is available on java 14 and above only. Although record classes provide some basic ways for doing things faster we should not use it in every other case and as an alternative to lombok. You can read this detailed blog for more comparison.
Conclusion
Many languages provide so many built-in features and if we use them wisely we can simplify our code. Record classes is one such feature in java. Link for github url for source code can be found here.