Search code examples
javamicronaut

How to enable eager singleton initialization for tests in Micronaut?


I have a case where I have a @Factory annotated class which creates a bean and invokes some code. I have enabled eager singleton initialization and the bean factory method is invoked even though it is not used anywhere when the application is started. However for tests, the eager initialization does not work and the bean is not created :

Application :

public class Application {

    public static void main(String[] args) {
        Micronaut.build(args)
                .eagerInitSingletons(true)
                .mainClass(Application.class)
                .start();
    }
}

Config

@Factory
public class Config {

    @Singleton
    @Bean
    public Response response() {
        System.out.println("Invoked");
        //invoking some code
        return new Response("test");
    }
}

and the test :

@MicronautTest(application = Application.class)
class ApplicationSpec extends Specification {

    @Inject
    EmbeddedApplication<?> application

    void 'test it works'() {
        expect:
        application.running
    }

}

so when the test is executed, the response method from Config class is not invoked even though eagerInitSingletons is enabled and it works when the application is started normally.

The question is : How to enable eager singleton initialization for micronaut tests?


Solution

  • Can you try using a custom context builder?

    YourTest Class

    @MicronautTest(contextBuilder = CustomContextBuilder.class)
    

    Your CustomContextBuilder:

    public class CustomContextBuilder extends DefaultApplicationContextBuilder {
    
        public CustomContextBuilder() {
            eagerInitSingletons(true);
        }
    }