How to Test Micronaut Apps With MicronautTest and Mocks
Test a Micronaut application with MicronautTest, an injected HTTP client, mock beans and Test Resources that start real containers for databases.

Micronaut applications start fast, which changes how you can test them: starting the real application context and the embedded server inside a test costs a fraction of a second, so you can test through HTTP without mocking half the framework. The @MicronautTest annotation does the starting, injects beans and a client, and lets you swap pieces for fakes. This post shows three levels of tests from a plain unit test up to a controller backed by a real PostgreSQL started by Micronaut Test Resources, how to replace beans, how to override properties, and what to do about transactions. It uses Micronaut 4, JUnit 5 and JDK 25. For setting up a first project, see the Micronaut tutorial.
Dependencies
<dependency>
<groupId>io.micronaut.test</groupId>
<artifactId>micronaut-test-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-client</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>A project created with Micronaut Launch includes these. micronaut-test-junit5 brings the extension that manages the application context. The annotation processing for your own beans runs at compile time, so the test classes need the same processor configuration as main code if they define beans.
Level 1: a plain unit test
Most of the logic needs no framework. A service with a constructor and two collaborators is checked with new and Mockito, in milliseconds:
class DiscountServiceTest {
@Test
void gives_ten_percent_to_gold_customers() {
var loyalty = mock(LoyaltyClient.class);
when(loyalty.tier("c-1")).thenReturn(Tier.GOLD);
var service = new DiscountService(loyalty);
assertEquals(new BigDecimal("90.00"), service.price("c-1", new BigDecimal("100.00")));
}
}No annotation, no context. Constructor injection, which Micronaut encourages, is what makes this possible. Put business rules in plain classes and test them here, and keep the heavier levels for wiring and HTTP behaviour. The tradeoffs of mocking are discussed in when mocks help and when they leave tests meaningless.
Level 2: a controller through HTTP
@MicronautTest
class OrderControllerTest {
@Inject
@Client("/")
HttpClient client;
@Test
void returns_404_for_an_unknown_order() {
var request = HttpRequest.GET("/orders/999");
var ex = assertThrows(HttpClientResponseException.class,
() -> client.toBlocking().exchange(request));
assertEquals(HttpStatus.NOT_FOUND, ex.getStatus());
}
}@MicronautTest starts the application context and an embedded server on a random port before the tests of the class, and stops it afterwards. @Client("/") injects an HTTP client already pointed at that server. The test sends a real request through the real routing, filters, binding and serialisation, so a wrong @Produces or a missing validation shows up. The blocking client throws HttpClientResponseException for 4xx and 5xx responses, which is the usual way to assert an error status. To read a body, use client.toBlocking().retrieve(request, Order.class).
The context is cached across test methods in the class, and a new one is created for each class with different configuration, so many differently configured test classes cost startup time each. Group tests that share configuration. The declared transaction and lifecycle semantics are in the Micronaut Test guide.
Replace a bean with a mock
Swap a collaborator for a mock by declaring a replacement bean in the test:
@MicronautTest
class CheckoutTest {
@Inject @Client("/") HttpClient client;
@Inject PaymentGateway gateway;
@MockBean(PaymentGateway.class)
PaymentGateway gateway() {
return mock(PaymentGateway.class);
}
@Test
void charges_the_gateway_once() {
client.toBlocking().exchange(HttpRequest.POST("/checkout", new CheckoutRequest("c-1", "50.00")));
verify(gateway, times(1)).charge(any());
}
}@MockBean(PaymentGateway.class) on a method registers its return value as the bean for that type, replacing the real one for this test class. The injected gateway is the mock, so you can stub and verify. Micronaut's @Replaces does the same at a lower level, for a bean you write as a test double class with @Replaces(RealGateway.class), which suits a fake with state instead of a Mockito mock. Mocks are reset between tests by default.
Prefer fakes for collaborators with real behaviour (a repository, a clock) and mocks for interactions you want to verify. The same distinction applies in Spring, see replacing beans in Spring tests.
Level 3: a real database with Test Resources
A mock repository cannot show that the SQL, the mapping and the migration work. Micronaut Test Resources starts containers for the services your application needs, based on the configuration, without any setup in the test:
datasources:
default:
db-kind: postgresql
flyway:
datasources:
default:
enabled: trueWith the Test Resources module on the build (Micronaut Launch adds it) and no url configured, the first test run starts a PostgreSQL container, injects its URL, user and password into the datasources.default properties, and shares it across the test run. Flyway applies the migrations to it, and the test sees a real database of the production type. The mechanism is the same idea as Quarkus's Dev Services, described in Dev Services. It needs a container runtime, and when none is found the failure is the one in could not find a valid Docker environment. Containers start once per build, not per test, which keeps the cost to a few seconds. Details and the list of supported services are in the Test Resources guide.
Property overrides
Change configuration for one test class with @Property, or supply a map by implementing TestPropertyProvider:
@MicronautTest
@Property(name = "app.checkout.max-items", value = "3")
class LimitTest { /* ... */ }A test-specific application-test.yml is loaded when the test environment is active, which @MicronautTest activates. Use it for settings that every test shares, such as disabling schedulers or setting a short timeout, and @Property for the one that makes a case possible.
Transactions and rollback
@MicronautTest(transactional = true), the default, wraps each test method in a transaction that is rolled back at the end, so data written by one test does not leak into the next. That holds for work done on the test thread. A request made through the HTTP client runs on the server's thread in its own transaction and commits, outside the test's transaction. A test that posts data through HTTP and expects automatic cleanup will find the rows still there. Either set transactional = false and clean up explicitly in @AfterEach, or clean the tables with a repository call, or give each test its own data keyed by unique ids. Mixing the two styles in one class is a common source of tests that pass alone and fail in a suite.
Test slices are not needed
Spring has slice annotations that load part of the context, such as a web layer or a data layer. Micronaut has no equivalent, because the full context starts quickly and because dependency injection is resolved at compile time, so there is little to skip. The practical way to keep tests cheap is to keep the set of beans small: use @Requires conditions on optional components, put heavy integrations behind environment names such as test and prod, and avoid scanning large packages for beans that a test does not need. When a test needs only one bean, build it with new and test it at level one.
Debugging a failing context
When a @MicronautTest fails to start, the message names the bean that could not be created and the missing dependency, usually No bean of type [X] exists. Check that the dependency's class is annotated with a bean scope (@Singleton), that the annotation processor ran on the module that defines it, and that a @Requires condition on it is satisfied in the test environment. Run mvn clean after changing annotation processor settings, since stale generated classes in target hide the real error. A mock defined with @MockBean for a type that has no real bean in the context is accepted and masks a wiring problem that exists in production, so also run at least one test without the mock.
Where this does not apply
For a pure function or a small class, the first level is enough, and a context per test is waste. For performance testing, use a deployed instance. The strategy for balancing these levels is in a practical Java testing strategy.


