zonkyio / embedded-database-spring-test

A library for creating isolated embedded databases for Spring-powered integration tests.
Apache License 2.0
399 stars 37 forks source link

Automatically or programmatically set AutoConfigureEmbeddedDatabase on test class alongside SpringBootTest #225

Closed bobbyrne01 closed 1 year ago

bobbyrne01 commented 1 year ago

Hey, would you have any thoughts on this so question?

https://stackoverflow.com/questions/75249017/automatically-or-programmatically-set-autoconfigureembeddeddatabase-on-test-clas

Basically tried to use zonky.test.database.provider=zonky configuration property and it works but it requires the presence of AutoConfigureEmbeddedDatabase on each test class that has SpringBootTest already set.

Any other way of activating zonky embedded postgres as default database provider without having to annotate each test class with AutoConfigureEmbeddedDatabase?

tomix26 commented 1 year ago

Hi @bobbyrne01, yes, that's how this library works 🙂

Nevertheless, you have several options. You can keep using the annotation and just hide it somewhere. For instance, place it on a superclass or create and use a composed annotation (e.g. PostgresSpringBootTest).

Or the second and more technical approach. You can create an additional context customizer factory that registers EmbeddedDatabaseContextCustomizer even when the AutoConfigureEmbeddedDatabase annotation is missing. Check out the example below.

public class CustomEmbeddedDatabaseContextCustomizerFactory extends EmbeddedDatabaseContextCustomizerFactory {

    @Override
    public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) {
        Set<AutoConfigureEmbeddedDatabase> annotations = AnnotationUtils.getDatabaseAnnotations(testClass);

        if (annotations.isEmpty()) {
            return new EmbeddedDatabaseContextCustomizer(Set.of(
                    new DatabaseDefinition("", DatabaseType.AUTO, DatabaseProvider.DEFAULT)));
        }

        return null;
    }
}

To make it work, you have to add an entry to spring.factories like this: org.springframework.test.context.ContextCustomizerFactory=your.package.CustomEmbeddedDatabaseContextCustomizerFactory

tomix26 commented 1 year ago

I hope the solution I suggested helped. I'm closing the issue.