Skip to content
Go back

Test Automation - Improve Code Readability Using Java 13 Text Blocks

Published:

Introduction

In this article, I will review a Java 13 preview language feature called “Text Blocks” that will help us improve our code readability.

Programing languages: Java

Testing Framework: TestNG, REST Assured

What are text blocks?

From OpenJDK:

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over format when desired.

How can I use it?

To use this feature, we need to perform the following actions:

  1. upgrade our JDK to version 13 (I am using OpenJDK).
  2. Enable the usage of preview features.

Implementing the solution

First will take a look at a simple API test that sends a POST request and verifies the response status code.

@Test(description = "POST - Create New Hotel")
public void postCreateNewHotel() {
    given()
        .body("{\r\n" +
            "\"city\": \"Tel Aviv\",\r\n" +
            "\"description\": \"Automation Hotel\",\r\n" +
            "\"name\":\"Rose Hill Hotel\",\r\n" +
            "\"rating\":5\r\n" +
            "}")
    .when()
        .post("http://52.134.35.17:9090/hotels")
    .then()
        .assertThat()
        .statusCode(201);
}

Now, let’s implement our solution:

@Test(description = "POST - Create New Hotel")
public void postCreateNewHotel() {
    given()
        .body("""
            {
                "city": "Tel Aviv",
                "description": "Automation Hotel",
                "name": "Rose Hill Hotel",
                "rating": 5
            }
            """)
    .when()
        .post("http://52.134.35.17:9090/hotels")
    .then()
        .assertThat()
        .statusCode(201);
}

Our test code now looks cleaner and readable using this feature.

In conclusion

In this article, we reviewed a java 13 preview language feature called text blocks that helps us to improve our code readability.

Further reading on JDK 13 features can be found in this link.

Happy testing!


Suggest Changes

Ready to build your quality roadmap? Start Here


Previous Post
Test Automation - Hiding Secrets Using System Environment Variables
Next Post
Test Automation - Improve Code Readability Using Enumeration