Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Testing and Native Images

Testing with Micronaut Test

Write fast Micronaut tests with @MicronautTest, an embedded server, injected HTTP clients, @Property overrides and JUnit 5. Includes a runnable mini test harness stand-in.

Tests are how you change code without fear. Micronaut starts so fast that you can test against a real application context and a real embedded HTTP server in a second or two, instead of mocking everything away. The micronaut-test modules integrate this with JUnit 5, Kotest, Spock and others.

The real framework is not available on this site, so the Micronaut test code is read-only. The runnable examples build a miniature application and test harness in plain Java that imitates the idea: start the app once, call it through a client, assert on responses.

The test dependencies

With Gradle (Maven is similar), add JUnit 5 and the Micronaut test support:

GROOVY
testImplementation("io.micronaut.test:micronaut-test-junit5")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")

The generated project from the Micronaut launcher already contains these. Tests live in src/test/java and use the test environment, so application-test.yml is loaded automatically.

@MicronautTest

Annotate a test class and Micronaut starts the application context once for the class (and, with the same configuration, can share it with other classes). Beans can be injected straight into the test:

Java
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

@MicronautTest
class NoteControllerTest {

    @Inject
    @Client("/")
    HttpClient client;

    @Test
    void listIsInitiallyEmpty() {
        String body = client.toBlocking().retrieve("/notes");
        assertEquals("[]", body);
    }

    @Test
    void createReturns201() {
        var response = client.toBlocking()
                .exchange(HttpRequest.POST("/notes", new NewNote("Buy milk", "2 litres", 3)), Note.class);
        assertEquals(HttpStatus.CREATED, response.getStatus());
        assertEquals("Buy milk", response.body().title());
    }

    @Test
    void invalidBodyReturns400() {
        var e = assertThrows(HttpClientResponseException.class, () ->
                client.toBlocking().exchange(HttpRequest.POST("/notes", new NewNote("", "x", 99))));
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatus());
    }
}

Notes:

  • @Client("/") injects a client already pointed at the random port of the embedded server, so tests never clash on port 8080.
  • The blocking client throws HttpClientResponseException for 4xx and 5xx responses, which you assert with assertThrows. Use exchange if you need to inspect the status.
  • Prefer declaring a test client interface (@Client("/notes") interface NoteClient { ... }) for readable tests, and reuse the same interface style described for production in Service Discovery and Distributed Configuration.

One test, three layers

Unit test A class and its fakes. No context.
@MicronautTest Real beans, real wiring, embedded server.
1 / 2

Overriding properties

Often a test needs different settings. Use @Property on the class or a method, or a TestPropertyProvider for computed values:

Java
@MicronautTest
@Property(name = "app.page-size", value = "2")
class PagingTest { /* ... */ }

For each distinct set of properties Micronaut builds a separate application context. That is convenient but slower, so group tests that share configuration.

Test lifecycle and transactions

With a database module you can set @MicronautTest(transactional = true) (the default for data tests). Each test method runs in a transaction that is rolled back at the end, so tests cannot affect each other. Set transactional = false when the code under test starts its own transactions or runs on other threads, and clean up explicitly in @AfterEach.

Use @MicronautTest(rebuildContext = true) to build a fresh context for every method when a test changes global state. It is slower, so use it rarely.

Testing without a server

Not every test needs HTTP. If your controller is a plain bean you can inject it and call the method directly:

Java
@MicronautTest
class NoteServiceTest {

    @Inject NoteService service;

    @Test
    void findsNoteById() {
        Note saved = service.save(new NewNote("A", "B", 1));
        assertEquals("A", service.find(saved.id()).title());
    }
}

And for pure logic, use no framework at all: a plain unit test with new NoteService(fakeRepository). Constructor injection (see Beans and Singletons) makes this easy.

Try it: a miniature app and test client

This stand-in has a tiny in-memory application with routes, a client and a three-test harness. It imitates what @MicronautTest and the injected client do.

Java A mini HTTP test harness

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.

The last test fails on purpose: a previous test created a note, so the list is no longer empty. This is the classic test isolation bug. Transactional rollback, fresh contexts or explicit clean-up are how you avoid it, and Mocking and Test Resources shows more tools.

Try it: isolating tests

Java Reset state between tests

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.

Good habits

  • Name tests by behaviour: invalidBodyReturns400, not test1.
  • One reason to fail per test. Arrange, act, assert.
  • Test failure modes (validation, authorization, missing data), not only the happy path. Pair with Bean Validation and Security Fundamentals cases.
  • Keep slow, external-dependency tests few and in their own tagged group.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @MicronautTest do?

    It builds a real application context so that beans can be injected and the app tested with real wiring.
  2. 2. Why does the injected @Client("/") not clash with another test on port 8080?

    Micronaut picks a random port for tests and points the injected client at it.
  3. 3. What exception does the blocking HTTP client throw for a 400 response?

    4xx and 5xx responses raise HttpClientResponseException with the status.
  4. 4. How are tests with a database usually isolated from each other?

    Transactional tests roll back changes at the end of each method.

Summary

  • @MicronautTest starts a real context quickly; inject beans and an HttpClient into tests.
  • Override settings with @Property; different property sets create separate contexts.
  • Keep tests isolated with rollbacks or explicit clean-up.
  • Use plain unit tests for logic and @MicronautTest for wiring, HTTP and security behaviour.

Next: Mocking and Test Resources