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

Java Core › The language for tests

Modern Java for tests: var, enum, record and text blocks

enum, record, var and text blocks remove boilerplate in tests and move errors from run time to compile time. An enum gives a closed set of values, a record is an immutable data carrier with generated equals and toString, text blocks read like JSON or SQL, and var fits when the type is visible on the right side. A record holding a password overrides toString.

Java · Language

A piece of test data takes 25 lines of boilerplate. What does modern Java remove?

A test project written in the Java 8 style has a Credentials class with two fields, a constructor, getters, equals, hashCode and toString; environment constants as strings that somebody mistypes; a JSON request body glued together from escaped quotes. All of it works, but it hides the point of the test under boilerplate. String constants have long been replaced by enum (Java 5), and since Java 10 the language has gained var, records and text blocks, which remove the rest of this noise.

This lesson covers which of them are really useful in automation, how they work and where using them does harm. The examples target Java 21 (LTS); Java 25 is also an LTS (September 2025), and everything below works there too. The real project version is set by maven.compiler.release or the Gradle java.toolchain: do not turn on --enable-preview in tests, because preview features may change or disappear.

How it works and why it is designed so

All four tools (enum, record, var, text blocks) are the compiler's work: there are no new data types in bytecode, so they do not change test speed. Their value lies elsewhere: moving errors from run time to compile time and removing text that carries no meaning.

enum defines a closed set of values. The compiler will not accept a wrong constant Browser.CHOME, while the string "chome" would reach the middle of a run. An enum can hold fields and methods, for example the address of an environment.

enum Env {
    DEV("https://dev.example.com"),
    STAGE("https://stage.example.com");

    private final String baseUrl;

    Env(String baseUrl) { this.baseUrl = baseUrl; }

    String baseUrl() { return baseUrl; }

    /** Reads -Denv=stage; an unknown name throws at once. */
    static Env current() {
        return valueOf(System.getProperty("env", "dev").toUpperCase(Locale.ROOT));
    }
}

valueOf throws IllegalArgumentException for an unknown name: this is a fast failure at the start of a run with the wrong value in the message (No enum constant Env.QA), not strange behaviour in the middle of a scenario. The second gain is in a switch expression (Java 14+) over an enum: without a default branch the compiler demands that all constants are listed. When somebody adds PROD, the code stops compiling exactly where the branch was forgotten:

String label = switch (env) {
    case DEV -> "development";
    case STAGE -> "staging";
};

record (Java 16) is an immutable data carrier. From the declaration record Credentials(String email, String password) {} the compiler creates a constructor, the accessors email() and password(), and equals, hashCode and toString over all components. A record is implicitly final, cannot extend a class, but can implement interfaces. A component cannot be assigned again, but if the component is mutable (a List), its content can still change.

A boilerplate class and a record

Java 8

A 25-line class

Fields, constructor, getters, equals, hashCode, toString. A field was added and equals was not updated.

Java 16+

One record line

Components are declared once and the rest is generated from them, always consistent.

Figure 1. A record removes the code where errors hide.

A record can have a compact constructor to validate input and an overridden toString. The second matters more than it seems: the generated toString prints all components, so a password would land in the log and the report.

record Credentials(String email, String password) {
    Credentials {                       // compact constructor
        if (email == null || email.isBlank())
            throw new IllegalArgumentException("email is required");
    }

    @Override public String toString() { // do not print the password
        return "Credentials[email=" + email + ", password=***]";
    }
}

Jackson reads and writes records starting from 2.12, so the same type suits JSON data. If you need a mutable object, such as a Builder or an ORM entity, a record is not a fit.

var (Java 10) infers the type of a local variable from the right-hand side: var users = new ArrayList<User>();. The type stays static; this is not dynamic typing. Restrictions: only local variables with an initializer (not fields, not method parameters, not var x = null). A diamond trap: var list = new ArrayList<>(); gives ArrayList<Object>, because there is nothing to infer from. So var is fine when the type is visible on the right (new, a literal, a factory) and harmful when it is not: var data = service.load(); forces you to open the method to learn the type.

Text blocks (Java 15) are a multi-line string in triple quotes. The compiler removes the common indentation: it is set by the least indented line together with the closing quotes. Double quotes inside need no escaping (except three in a row), so JSON and SQL read as they are. Together with formatted (Java 15) you get a request body template:

String body = """
    {
      "email": "%s",
      "role": "%s"
    }
    """.formatted(user.email(), user.role());

The result ends with a newline because the closing quotes are on a new line. If the JSON contains a % character, formatted treats it as a specifier; for complex bodies it is more reliable to build an object and serialise it with Jackson.

Pattern matching. instanceof with a pattern (o instanceof User u, Java 16) removes the cast. Java 21 finalised switch with patterns and a when condition:

String describe(Object o) {
    return switch (o) {
        case Integer i when i > 0 -> "positive " + i;
        case Integer i -> "int " + i;
        case String s -> "text " + s;
        case null -> "null";
        default -> "other";
    };
}

In tests this is handy for parsing a response of arbitrary shape or results of different types, but ordinary checks rarely need it.

Limits and alternatives. This is only syntax: if the project is pinned to Java 11 or 17, some of the tools are unavailable (record since 16, text blocks since 15, pattern switch since 21), so check the language level before taking code from examples. For mutable data with many optional fields a Builder is better, and in some teams Lombok stays instead of a record for compatibility with old code.

Common mistakes

  • Strings instead of an enum for a browser or environment: a typo is found only at run time.
  • default in a switch over an enum "just in case": the compiler no longer reminds you of a new constant.
  • A record with a password and no overridden toString: the secret lands in the logs.
  • var where the type is unclear, or var list = new ArrayList<>() with an unexpected Object.
  • A text block whose indentation an editor changed: the indentation depends on the closing quotes, and stray spaces end up in the JSON.

Check yourself

A switch expression over the enum Env had its default removed, and then a constant PROD was added. What happens and why is it good?

Answer

The code stops compiling: a switch expression without default must cover all constants. The compiler finds the place with the forgotten branch, not a test run.

What type does var list = new ArrayList<>(); have and why?

Answer

ArrayList<Object>: the diamond infers the type parameter from context, and var gives none. Write new ArrayList<User>() or an explicit variable type.

Why should a record that holds a password override toString?

Answer

The generated toString prints all components, so any log or failure message would show the password in plain text.

In an interview. Junior: I use enum for browsers and environments, record for test data, and var only where the type is visible on the right. Text blocks are handy for JSON bodies. Middle/Senior: I understand that this is the compiler's work: a mistake in a constant or a forgotten branch of a switch without default becomes a compile error. In a record I override toString if it holds a secret, and I remember that it is immutable only shallowly. I take the language level from the build configuration (Java 21 LTS or newer), with no preview features in tests.

More articles in this chapter