Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Testing and Deployment

Testing with @QuarkusTest and REST Assured

Test Quarkus applications with @QuarkusTest, REST Assured, injection into tests, @TestTransaction and Dev Services databases, plus integration tests of the packaged app.

A service that is easy to write but hard to test will rot. Quarkus keeps tests close to production: a @QuarkusTest starts the real application once, with real CDI, real configuration and a real HTTP server on a test port, and your JUnit 5 tests call it. Dev Services supplies a real PostgreSQL (or Kafka, Keycloak, ...) in a container, so you are not testing against a different database than you deploy.

This lesson shows the anatomy of a Quarkus test, REST Assured for HTTP assertions, injecting beans into tests, database rollback, and the integration-test flavor that tests the packaged jar or native executable. Continue with mocks and test profiles afterwards. Quarkus cannot run here, so tests are read-only, and the TryIts implement a mini server and a mini REST Assured with the JDK so you can see what the assertions do. If you need a JUnit refresher, see JUnit and TestNG.

Setup

Add two test dependencies and you are ready:

XML
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-junit5</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>rest-assured</artifactId>
  <scope>test</scope>
</dependency>

A project generated from code.quarkus.io already has them. Tests live in src/test/java and use the test profile, so %test. keys apply (see profiles).

The first test

Java
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

@QuarkusTest
class BookResourceTest {

    @Test
    void listsBooks() {
        given()
          .when().get("/books")
          .then()
             .statusCode(200)
             .body("size()", greaterThan(0))
             .body("[0].title", notNullValue());
    }

    @Test
    void createsBook() {
        given()
          .contentType("application/json")
          .body("{\"title\":\"Quarkus in Action\",\"pages\":420}")
          .when().post("/books")
          .then()
             .statusCode(201)
             .header("Location", containsString("/books/"));
    }
}

What happens behind this small class:

  1. Quarkus starts the application once for the whole test run, not once per test class. Tests that share the same configuration share the same running app, which is why Quarkus test suites are fast.
  2. The HTTP server listens on port 8081 (the quarkus.http.test-port), and REST Assured is pre-configured to use it. Set quarkus.http.test-port=0 to pick a random free port.
  3. Each given().when().then() call is a real HTTP request over the loopback interface, with real serialization, filters, validation and exception mappers.

@TestHTTPEndpoint(BookResource.class) removes the repeated path: with it, get() or get("/{id}", 7) is relative to the resource's @Path.

Anatomy of a Quarkus test

Start once One app for many tests.
Dev Services Real PostgreSQL in a container.
Real HTTP REST Assured on the test port.
Clean up Roll back or reset state.

Closer to production, still fast.

1 / 2
Java Stand-in: a tiny server and a REST Assured style DSL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Injecting beans into tests

A @QuarkusTest class is itself a CDI bean, so you can inject anything the application has:

Java
@QuarkusTest
class PriceCalculatorTest {

    @Inject PriceCalculator calculator;

    @Test
    void addsTax() {
        assertEquals(119, calculator.withTax(100));
    }
}

This is useful for testing services directly, without HTTP, while still using real configuration and Dev Services.

Database tests and cleanup

Tests share one application and one database, so they can disturb each other. Three habits keep them independent:

  1. @TestTransaction on a test method wraps it in a transaction that is rolled back at the end. Anything the test persists vanishes.
  2. A known starting state. Load fixtures in @BeforeEach (for example Book.deleteAll() then persist a few rows) or via %test.quarkus.hibernate-orm.sql-load-script=import-test.sql.
  3. Unique data. Tests that must commit can use random names or ids, so parallel runs do not collide.
Java
@QuarkusTest
class BookRepositoryTest {

    @Inject BookRepository books;

    @Test
    @TestTransaction
    void persistsAndFinds() {
        Book saved = books.save(new Book("Native Quarkus", 310));
        assertNotNull(saved.id);
        assertEquals(1, books.count("title", "Native Quarkus"));
    }   // rolled back here
}

@TestTransaction works for blocking Panache code on the test thread. Reactive code (Hibernate Reactive) uses @RunOnVertxContext and UniAsserter from quarkus-test-vertx instead.

Java Stand-in: transaction rollback keeps tests independent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Integration tests of the packaged app

@QuarkusTest runs your code in the same JVM as the test. That makes mocking and injection possible, but it also means the packaged jar or the native executable is never what was tested. @QuarkusIntegrationTest closes that gap: it runs package, starts the real artifact as a separate process and tests it over HTTP only (no injection). Failsafe runs these in the verify phase:

Java
@QuarkusIntegrationTest
class BookResourceIT extends BookResourceTest { }   // reuse the same assertions
Terminal
./mvnw verify                       # unit + integration tests on the jar
./mvnw verify -Dnative              # integration tests on the native executable

Useful practices

  • Keep most tests as plain JUnit: a pure class such as a price calculator needs no application at all and runs in milliseconds.
  • Use @QuarkusTest for endpoints, wiring, validation, persistence and security.
  • Print less, assert more: with REST Assured, use .log().ifValidationFails() to see the request and response only when an assertion fails.
  • Use continuous testing (r in dev mode) while you work, see dev mode.
  • In CI, make sure Docker is available, otherwise Dev Services cannot start the database container.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How often does Quarkus start the application during a test run of many @QuarkusTest classes?

    Tests with the same profile and resources share one running application, which keeps suites fast.
  2. 2. What does @TestTransaction do?

    The rollback removes data written during the test so tests stay independent.
  3. 3. Which statement about @QuarkusIntegrationTest is true?

    The application runs outside the test JVM, so injection and mocking are unavailable but the real artifact is verified.
  4. 4. Why does Quarkus recommend Dev Services in tests instead of an in-memory H2 database?

    Real PostgreSQL behavior (types, locking, SQL dialect) avoids surprises that only show up in production.

Summary

  • @QuarkusTest starts the real application once and tests it over HTTP with REST Assured.
  • Inject beans into the test class; use @TestTransaction and fixtures to keep tests independent.
  • Dev Services gives tests a real database or broker in a container.
  • @QuarkusIntegrationTest verifies the packaged jar or native executable.
  • Keep pure logic in plain JUnit tests.

Next: Mocks, Test Profiles and Test Resources