Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Testing and Native Images

Mocking, @MockBean and Test Resources

Replace beans in tests with @MockBean and @Replaces, use Mockito or hand-written fakes, and start real databases with Micronaut Test Resources and Testcontainers.

A good test controls what it depends on. A service that sends an email, charges a card or calls another team's API should not do so for real while your test suite runs. You replace that dependency with a test double: a mock that records calls and returns canned answers, or a fake that behaves like the real thing in a simpler way. Micronaut makes replacing beans easy because the wiring is explicit.

The real framework is read-only on this site. The TryIt examples use plain Java to show the techniques (a mock that records calls, a fake that behaves like a store, and a replacement registry), so you can practise the ideas without a build tool.

Mocks, stubs and fakes

  • A stub returns fixed answers.
  • A mock also records how it was called, so the test can verify the interaction (verify(mailer).send(...)).
  • A fake is a working lightweight implementation, such as an in-memory repository.

Prefer fakes and real beans where possible; use mocks for edges that are slow, costly or unsafe (email, payments, clocks).

@MockBean

The classic Micronaut Test approach is a method annotated with @MockBean that returns the replacement for a given bean type. It lives inside the test class and replaces the real bean for that test's context:

Java
import io.micronaut.test.annotation.MockBean;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import jakarta.inject.Inject;

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

@MicronautTest
class OrderServiceTest {

    @Inject OrderService orders;
    @Inject PaymentGateway gateway;          // this is the mock below

    @MockBean(HttpPaymentGateway.class)      // replace the real implementation
    PaymentGateway paymentGateway() {
        return mock(PaymentGateway.class);
    }

    @Test
    void chargesTheCardOnce() {
        when(gateway.charge("card-1", 2500)).thenReturn(true);

        Order order = orders.place("card-1", 2500);

        assertEquals("PAID", order.status());
        verify(gateway, times(1)).charge("card-1", 2500);
    }
}

Mockito is added with testImplementation("org.mockito:mockito-core"). Because the injected gateway is the same mock instance the service received, you can program it and verify it.

Micronaut 4 also lets you do this without extra annotations using @Replaces on a test-scoped bean, which is the same mechanism you met in Conditional Beans with @Requires:

Java
@Singleton
@Replaces(HttpPaymentGateway.class)
@Requires(env = "test")
class FakePaymentGateway implements PaymentGateway {
    final List<Integer> charges = new ArrayList<>();
    public boolean charge(String card, int cents) { charges.add(cents); return true; }
}

Put it in src/test/java so it exists only in tests, and the @Requires(env = "test") is then optional. For a class that cannot be changed (a library bean), @Replaces with a @Factory works too.

Choosing a double

Stub Fixed answers. Simple.
Mock Records calls so you can verify them.
1 / 2

Try it: a hand-written mock

You can write a mock without a library, which makes clear what Mockito does. This recording gateway lets the test verify the interaction.

Java A recording mock

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.

Try it: replacing a bean in a registry

This stand-in has a tiny container where a test registers a replacement for a production bean, which is the essence of @Replaces and @MockBean.

Java Swap a bean for a test

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.

Real databases with Test Resources

Mocks cannot tell you whether your SQL works. For repositories, test against a real database engine. Micronaut Test Resources starts containers for you (using Testcontainers under the hood) and injects their addresses into your configuration, so the test needs no manual setup. Add the test-resources plugin to the build, and supply the client library; the matching container is chosen automatically:

GROOVY
plugins {
    id("io.micronaut.test-resources") version "4.5.0"
}
dependencies {
    runtimeOnly("org.postgresql:postgresql")
    testImplementation("org.testcontainers:postgresql")
}
YAML
datasources:
  default:
    # no url, username or password: they are provided by the test resource
    dialect: POSTGRES

When the test starts, the plugin launches a PostgreSQL container (Docker must be installed), fills in datasources.default.url and the credentials, and shares the container between tests (and between runs in dev mode). The same mechanism exists for MySQL, MongoDB, Kafka, RabbitMQ, Redis, Vault and more. Keep the production application.yml free of test URLs, and set production values by environment variables.

Other options for database tests are an in-memory H2 database (fast but not identical to production) or an explicitly managed Testcontainers @Testcontainers class if you need a custom image.

Time, randomness and other hidden inputs

Tests that depend on the current time or a random number are flaky. Inject a java.time.Clock bean and replace it with Clock.fixed(...) in tests; inject a random source and replace it with a seeded one. The @Requires(missingBeans = Clock.class) default pattern from the earlier lesson makes this natural.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a mock and a fake?

    Mocks are used to verify interactions. Fakes, like in-memory repositories, behave like the real thing in a lighter way.
  2. 2. What does @MockBean do in a Micronaut test?

    The method's return value is used instead of the real bean in that test's context.
  3. 3. Why use a real database container for repository tests?

    Only a real engine verifies queries, constraints and migrations.
  4. 4. How do you make a test that depends on the clock deterministic?

    An injected fixed Clock gives the code a predictable time.

Summary

  • Replace slow, costly or unsafe dependencies with stubs, mocks or fakes.
  • @MockBean (with Mockito) and @Replaces swap beans in the test context.
  • Micronaut Test Resources starts real containers and injects their URLs, so repository tests run against a real engine.
  • Make clocks and randomness injectable so tests are deterministic.

Next: GraalVM Native Image Basics