Micronaut testing with mock beans and clients

In real-world testing, you often need to isolate your code from external dependencies:

  • External APIs
  • Databases
  • Message brokers
  • Remote services

βœ… This is where mocking becomes very important.
βœ… Micronaut testing with mock beans and clients makes it easy to isolate and verify application logic without relying on external systems.

In our last post we saw Writing Integration Tests with Embedded Server

In this post, we’ll cover:

  • Why mocking is important
  • Mocking services
  • Mocking HTTP clients
  • Mocking beans for integration tests
  • Best practices
Micronaut testing with mock beans and clients

πŸ— Why Mock in Tests?

ProblemSolution
Slow external callsMock responses
Unstable remote servicesIsolate tests
Complex DB setupFake repositories
Testing edge casesCustom mock behavior

πŸš€ Project Setup

Assume you have a basic Micronaut project already set up.

You need these dependencies in your Maven pom.xml:

🏫 Sample Use Case

Let’s say we have a WeatherService that calls an external weather API:

We want to mock this service while testing a controller that uses it.

πŸ§ͺ Mocking Beans in Micronaut

Micronaut provides @MockBean annotation to replace real beans during tests.


βœ… Example Controller

βœ… Integration Test with Mocked Bean

βœ… Registering the MockBean

You must tell Micronaut to replace the original bean with a mock:

βœ… This ensures:

  • Micronaut replaces original WeatherService with mock.
  • The mock participates in dependency injection.
  • You can inject it directly and configure its behavior.

πŸ”¬ Mocking HTTP Clients (@Client)

Micronaut also allows you to mock HTTP clients used for external API calls.

βœ… Sample Client

βœ… Service that uses the client

βœ… Test with Mocked HTTP Client

βœ… Register MockBean for HTTP Client

⚠ Common Mistakes

ProblemCauseSolution
Real bean still usedMockBean not registeredUse @MockBean properly
NullPointerException on injectionIncorrect bean scopeEnsure proper injection
Mockito errorMixing static methodsUse Mockito for interface or class mocks

🧰 Best Practices for Micronaut testing with mock beans and clients

βœ… Always separate unit tests and integration tests.
βœ… Mock external systems β€” not your own service logic.
βœ… Use Micronaut’s @MockBean instead of Mockito’s standalone @Mock.
βœ… Avoid over-mocking β€” sometimes better to test full stack.
βœ… Use application-test.yml for isolated config.

🌐 External References