Post

Inject REST Assured Specifications With a JUnit Extension

Replace static configuration and set-up code with a JUnit 6 extension that starts the API once per class, injects ready-made request and response specifications into test methods, and closes the API through the extension store.

Inject REST Assured Specifications With a JUnit Extension

Every test class in your suite starts the same way: a static field for the API, @BeforeAll to start it, @AfterAll to stop it, and a specification to point requests at it. That’s ten lines of set-up, copied into every class. Moving it into static defaults on RestAssured removes the copies, but adds global state that breaks the moment classes run in parallel. In this guide, you’ll write a JUnit 6 extension that starts the API and injects ready-made specifications, so a test class needs one annotation and no set-up at all.

Level: Intermediate · Time: 25 minutes · Part of: Module 5: Reusable Specifications and Configuration, section 5

What You’ll Build

You’ll build three files: a composed annotation, @OpenBankingApiTest; an extension, OpenBankingApiExtension, that starts the API and resolves parameters; and a test class, InjectedSpecificationTest, with three tests that receive their specifications as parameters.

The finished test class has no fields, no lifecycle methods and no static state:

1
2
3
4
5
6
7
8
9
@OpenBankingApiTest
class InjectedSpecificationTest {

    @Test
    void listAccounts(RequestSpecification openBanking, ResponseSpecification ok) {
        given(openBanking).when().get("/accounts").then().spec(ok).body("Data.Account", hasSize(3));
    }
    ...
}

When you’re done, Maven reports three passing tests:

1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Write a composed annotation.
  • Start the API once per class.
  • Resolve specifications as parameters.
  • Write tests without set-up.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Build Reusable Request Specifications in REST Assured.

Out of scope: this guide doesn’t cover running test classes in parallel, or selecting them by tag in a build; they’re taught in Module 12.

Understand JUnit Extensions for REST Assured

The problem. Set-up code repeated in every test class drifts, and every class that forgets to stop its API leaks a server. Static defaults avoid the repetition but make every class share the same REST Assured state, so classes can’t run in parallel, and a test that depends on another class’s defaults fails on its own.

The concept. A JUnit 6 extension plugs into the test lifecycle. OpenBankingApiExtension implements two extension points:

  • BeforeAllCallback: before the first test of a class, it starts the API and keeps it in the class’s extension store.
  • ParameterResolver: when a test method or constructor has a parameter of a supported type, it supplies the value.

It supports three parameter types:

Parameter typeWhat the test gets
RequestSpecificationThe API’s address, a bearer token, JSON, a fresh x-fapi-interaction-id and request logging
ResponseSpecificationThe expectations of a successful response: 200 and JSON
OpenBankingApiThe running API itself

A composed annotation bundles the extension and a tag, so a test class needs one line of set-up.

When to use it. Write an extension once a suite has several test classes against the same API. It gives every class its own API and every test its own specifications, with no static state, which is what makes parallel runs safe.

Keep set-up in an extension, and state in the extension store, never in static fields.

Meet the API Under Test

The tests use the Open Banking API from Build Reusable Request Specifications in REST Assured: GET /accounts returns three accounts, and GET /accounts/40114 returns the business account. Every request needs a bearer token and an x-fapi-interaction-id, which the extension’s request specification supplies.

Your tests check these values:

  • Data.Account, which has three accounts.
  • Data.Account[0].AccountType of account 40114, "Business".
  • The x-fapi-interaction-id of two injected specifications, which must differ.

Write a Composed Annotation

Bundle the Extension and a Tag

Goal: create one annotation that registers the extension and tags the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.javanibble.module_05.section_05.support;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(OpenBankingApiExtension.class)
@Tag("api")
public @interface OpenBankingApiTest {
}

What’s happening:

  • @ExtendWith(OpenBankingApiExtension.class) registers the extension for every class with this annotation.
  • @Tag("api") tags those classes, so every API test can be selected or excluded by tag.
  • @Retention(RUNTIME) keeps the annotation at runtime, where JUnit looks for it.

Checkpoint: the annotation won’t compile until the extension exists, in the next step.

Start the API Once per Class

Keep the API in the Extension Store

Goal: create the extension, and start the API before the first test of each class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.javanibble.module_05.section_05.support;

import com.javanibble.openbanking.OpenBankingApi;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;

import java.util.UUID;

import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;

public class OpenBankingApiExtension implements BeforeAllCallback, ParameterResolver {

    private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(OpenBankingApiExtension.class);

    @Override
    public void beforeAll(ExtensionContext context) {
        context.getStore(NAMESPACE).computeIfAbsent(OpenBankingApi.class, key -> OpenBankingApi.start(), OpenBankingApi.class);
    }
}

What’s happening:

  • The store belongs to the test class’s context, so each class gets its own API on its own port.
  • NAMESPACE keeps this extension’s entries apart from other extensions’ entries in the same store.
  • computeIfAbsent(key, creator, type) starts the API only if the store doesn’t have one yet.
  • There’s no AfterAllCallback. OpenBankingApi implements AutoCloseable, and JUnit closes AutoCloseable values in a store when the class’s context is closed, so the API stops after the last test of the class.

Checkpoint: the extension won’t compile yet, because it doesn’t implement the ParameterResolver methods. You’ll add them in the next step.

Use computeIfAbsent(..). In JUnit 6, getOrComputeIfAbsent(..) still works, but it’s deprecated, and computeIfAbsent(key, creator, type) replaces it.

Don’t keep the API in a static field of the extension. A static field is shared by every class that uses the extension, so classes would share one API, and parallel runs would break. Keep state in the extension store, as this step does.

Resolve Specifications as Parameters

Supply Specifications and the API

Goal: tell JUnit which parameters the extension supports, and build a value for each one.

Add these two methods to OpenBankingApiExtension:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Override
public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
    Class<?> type = parameter.getParameter().getType();
    return type == RequestSpecification.class || type == ResponseSpecification.class || type == OpenBankingApi.class;
}

@Override
public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
    OpenBankingApi api = context.getStore(NAMESPACE).get(OpenBankingApi.class, OpenBankingApi.class);
    Class<?> type = parameter.getParameter().getType();
    if (type == OpenBankingApi.class) {
        return api;
    }
    if (type == ResponseSpecification.class) {
        return new ResponseSpecBuilder()
                .expectStatusCode(200)
                .expectContentType(ContentType.JSON)
                .build();
    }
    return new RequestSpecBuilder()
            .setBaseUri(api.baseUri())
            .setPort(api.port())
            .setBasePath(OpenBankingApi.BASE_PATH)
            .setAccept(ContentType.JSON)
            .addHeader("Authorization", "Bearer test-token")
            .addHeader("x-fapi-interaction-id", UUID.randomUUID().toString())
            .log(LogDetail.ALL)
            .build();
}

What’s happening:

  • supportsParameter(..) tells JUnit which parameters this extension can fill. It looks only at the type, so parameter names are free to choose.
  • resolveParameter(..) finds the API that beforeAll(..) started: a test method’s context can see the store of its class.
  • It builds a new specification for every parameter it resolves, so each one gets a fresh interaction id, which one shared specification couldn’t do.

Checkpoint: the annotation and the extension now compile. There are no tests yet, so there’s nothing to run until the next step.

.log(LogDetail.ALL) on a RequestSpecBuilder logs every request made with the specification, whether the test passes or fails, and that log includes the token in full: Authorization=Bearer test-token. That’s acceptable for this course API’s fixed test token. For a real suite, log only on failure and blacklist the secret headers in the specification’s config, as Keep Secrets Out of REST Assured Logs teaches, so every test that uses the extension gets both.

Write Tests Without Set-Up

List and Read Accounts

Goal: write a test class with one annotation, whose tests receive their specifications as parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javanibble.module_05.section_05;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

import com.javanibble.module_05.section_05.support.OpenBankingApiTest;

import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import io.restassured.specification.SpecificationQuerier;

import org.junit.jupiter.api.Test;

@OpenBankingApiTest
class InjectedSpecificationTest {

    @Test
    void listAccounts(RequestSpecification openBanking, ResponseSpecification ok) {
        given(openBanking)
        .when()
            .get("/accounts")
        .then()
            .spec(ok)
            .body("Data.Account", hasSize(3));
    }

    @Test
    void readOneAccount(RequestSpecification openBanking, ResponseSpecification ok) {
        given(openBanking)
        .when()
            .get("/accounts/{id}", "40114")
        .then()
            .spec(ok)
            .body("Data.Account[0].AccountType", equalTo("Business"));
    }
}

What’s happening:

  • @OpenBankingApiTest is the class’s only set-up.
  • Each test declares the parameters it needs, and the extension supplies them: openBanking for the request, ok for the response.
  • Compare this with Send Your First REST Assured Request: the set-up has gone, and each test says only what it’s about.

Checkpoint: run InjectedSpecificationTest from your IDE. Two tests run and pass, and each logs its request.

Get a Fresh Specification per Parameter

Goal: prove that two injected specifications have different interaction ids.

Add this test to InjectedSpecificationTest:

1
2
3
4
5
6
7
@Test
void everyTestGetsItsOwnInteractionId(RequestSpecification first, RequestSpecification second) {
    String firstId = SpecificationQuerier.query(first).getHeaders().getValue("x-fapi-interaction-id");
    String secondId = SpecificationQuerier.query(second).getHeaders().getValue("x-fapi-interaction-id");

    assertNotEquals(firstId, secondId);
}

What’s happening:

  • Each parameter is resolved separately, so even two parameters in one test get different specifications.
  • SpecificationQuerier reads the header back, without sending a request.

Checkpoint: run the class again. All three tests pass.

Because nothing is static, test classes don’t share any REST Assured state. Add a second class with @OpenBankingApiTest, and it gets its own API on its own port: in one run, the two classes’ APIs listened on ports 57656 and 57658. That’s what makes parallel runs safe.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-05 -Dtest=InjectedSpecificationTest

You should see the two logged requests, followed by a result similar to the following:

1
2
3
4
5
6
7
[INFO] Running com.javanibble.module_05.section_05.InjectedSpecificationTest
...
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.022 s -- in com.javanibble.module_05.section_05.InjectedSpecificationTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

Delete the @OpenBankingApiTest line above class InjectedSpecificationTest and run the command again. You should see a result similar to the following:

1
2
3
4
[ERROR] Errors:
[ERROR]   InjectedSpecificationTest.listAccounts(RequestSpecification, ResponseSpecification) » ParameterResolution No ParameterResolver registered for parameter [io.restassured.specification.RequestSpecification openBanking] in method [...]
[ERROR]   InjectedSpecificationTest.readOneAccount(...) » ParameterResolution No ParameterResolver registered for parameter [...]
[ERROR]   InjectedSpecificationTest.everyTestGetsItsOwnInteractionId(...) » ParameterResolution No ParameterResolver registered for parameter [...]

Without the annotation, no extension is registered, so JUnit has nothing to fill the parameters with. All three tests are errors before they send a request. The message names the parameter and its type, which tells you which resolver is missing.

Put @OpenBankingApiTest back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
ParameterResolution No ParameterResolver registered for parameter [...]The class has no @OpenBankingApiTest, or the parameter’s type isn’t supportedAdd the annotation, or support the type in supportsParameter(..)
Two tests get the same interaction idThe extension returns one shared specificationBuild a new specification in resolveParameter(..)
Tests interfere when classes run in parallelThe extension keeps state in a static fieldKeep the API in the extension store
Every request, and its token, appears in the logThe request specification uses .log(LogDetail.ALL)Log on failure, and blacklist secret headers

Try It Yourself

Exercise 1: Inject the API Itself

Add a test called theSpecificationPointsAtTheInjectedApi that receives both the OpenBankingApi and a RequestSpecification. Check with SpecificationQuerier that the specification’s port is the API’s port, that its base path is OpenBankingApi.BASE_PATH, and that it carries the bearer token.

Hint

Declare both as parameters. QueryableRequestSpecification has getPort(), getBasePath() and getHeaders().

Solution
1
2
3
4
5
6
7
8
@Test
void theSpecificationPointsAtTheInjectedApi(OpenBankingApi api, RequestSpecification openBanking) {
    QueryableRequestSpecification query = SpecificationQuerier.query(openBanking);

    assertEquals(api.port(), query.getPort());
    assertEquals(OpenBankingApi.BASE_PATH, query.getBasePath());
    assertEquals("Bearer test-token", query.getHeaders().getValue("Authorization"));
}

Add imports for OpenBankingApi, QueryableRequestSpecification and assertEquals to the class.

Exercise 2: Inject Through the Constructor

The extension also resolves constructor parameters. Add a test class called ConstructorInjectionTest with @OpenBankingApiTest, whose constructor receives a RequestSpecification and keeps it in a field. Add a test that receives a ResponseSpecification, reads the balances of account 31820 with the field’s specification, and checks that the first balance is in "EUR".

Hint

JUnit creates a new instance of the test class for every test, so a constructor parameter is resolved again for each one, and each test still gets its own interaction id.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@OpenBankingApiTest
class ConstructorInjectionTest {

    private final RequestSpecification openBanking;

    ConstructorInjectionTest(RequestSpecification openBanking) {
        this.openBanking = openBanking;
    }

    @Test
    void balancesAreInEuro(ResponseSpecification ok) {
        given(openBanking)
        .when()
            .get("/accounts/{id}/balances", "31820")
        .then()
            .spec(ok)
            .body("Data.Balance[0].Amount.Currency", equalTo("EUR"));
    }
}

Summary

You built @OpenBankingApiTest, OpenBankingApiExtension and InjectedSpecificationTest, which together start the API once per class and give every test its own specifications, with no set-up code and no static state. The ten lines of set-up per class are now one annotation.

  • A JUnit 6 extension replaces repeated set-up code and static REST Assured configuration.
  • BeforeAllCallback starts the API once per class and keeps it in the extension store with computeIfAbsent(..); JUnit closes it because it’s AutoCloseable.
  • ParameterResolver gives test methods and constructors their own request and response specifications, including per-request values such as an interaction id.
  • A composed annotation registers the extension and a tag in one line per class.
  • Because no state is static, each class gets its own API, and classes can run in parallel; keep logging and secrets in mind when one specification serves every test.

Here are the commands you used in this guide:

1
mvn test -pl module-05 -Dtest=InjectedSpecificationTest

What’s Next

Next: you’ve completed Module 5. Continue with Module 6: Schema and Contract Validation, starting with Validate Responses Against a JSON Schema in REST Assured, which validates whole responses against a schema.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.