There are several options how to mock beans in your tests.


How to Mock Micronaut Beans in Tests

There are several options how to mock beans in your tests.

I prefer the last option as this is a very lightweight solution and you don’t have to use any external library nor you don’t have to write your own stubs.

Probably in every generated test you can find the following statement somewhere:

ApplicationContext.run(EmbeddedServer)

This is actually a simplified version of building the application context which can be expanded to a couple of following lines:

ApplicationContext
.build() // create the context builder .build() // build the context .start() // start the context .getBean(EmbeddedServer) // obtain the server bean .start() // run the server

Before starting the context you can easily register the mock bean:

ApplicationContext
.build() // create the context builder .build() // build the context .registerSingleton(OrganizationDataService, dataService)
.start() // start the context .getBean(EmbeddedServer) // obtain the server bean .start() // run the server

When the context will be asked for OrganizationDataService bean then it will find it already present in the context and will not instantiate the regular bean you are trying to mock.

This solution might look ugly but in many situations, you don’t need to start any bean such as EmbeddedServer. In that case, the solution will be much simpler:

ApplicationContext ctx = ApplicationContext.build().build() .registerSingleton(OrganizationDataService, dataService)
.start()UnderTestService uts = ctx.getBean(UnderTestService)