1

I'm trying to find any analogue of spring's @ContextConfiguration annotation in micronaut framework

Is there any way to run unit test in micronaut using custom application context? My project is a library without main class. I have @Factory with initialization of my beans.

@Factory
public class TestConfig {
@Singleton
public QueryParameterParser queryParameterParser() { }
@Singleton
public ConnectionHolder connectionHolder(DataSource dataSource) {  }
@Singleton
public QueryExecutor queryExecutor(ConnectionHolder connectionHolder, QueryParameterParser parameterParser) { }
}

In spring I'd write these for using context in test:


@ContextConfiguration(classes = TestConfig.class)
public class FunctionTest {
@Autowired
private TransactionExecutor transactionExecutor;

The only way to do it in micronaut I've found is to create CustomContextBuilder:


@Introspected
public class CustomContextBuilder extends DefaultApplicationContextBuilder {
private TestConfig factory = new TestConfig();

    public CustomContextBuilder() {
        TestConfig.DataBase db = factory.db();
        DataSource dataSource = factory.dataSource(db);
        singletons(
                db, dataSource,
                queryParameterParser,
                connectionHolder,
                new MicronautFixturesTestExecutionListener()
        );
    }

and pass CustomContextBuilder to @MicronautTest annotation. It works but is too complicated to write code for instantiating every bean in CustomContextBuilder everytime.

Is there any way to pass my @Factory class to context and not to write all singletons? I've tried package method and passed my @Factory package - but it didn't created context properly.

  • "Is there any way to run unit test in micronaut using custom application context?" - Yes. One way to do that is by way of the `contextBuilder` attribute of `@MicronautTest`. https://github.com/micronaut-projects/micronaut-test/blob/master/test-junit5/src/main/java/io/micronaut/test/extensions/junit5/annotation/MicronautTest.java#L93 – Jeff Scott Brown Nov 03 '22 at 14:26

0 Answers0