user3960875
user3960875

Reputation: 1005

Dropwizard integration testing with Testcontainers

I'm trying to run dropwizard's integration tests against a dockered database.

What I've tried:

@ClassRule
public static final PostgreSQLContainer postgres = new PostgreSQLContainer();

@ClassRule
    public final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
            ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
            ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
    );

I get Caused by: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started

Chaining these together does not work either

@ClassRule
    public static TestRule chain = RuleChain.outerRule(postgres = new PostgreSQLContainer())
            .around(RULE = new DropwizardAppRule<>(
                    Application.class,
                    CONFIG_PATH,
                    ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
                    ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
                    ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
            ));

Finally this works, but as I understand it runs the new DropwizardAppRule for every test and this is not good...

@ClassRule
public static final PostgreSQLContainer postgres = new PostgreSQLContainer();

@Rule
    public final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
            ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
            ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
    );

So how can I chain the rules such that PostgreSQLContainer is initiated first and container has started before creating the DropwizardAppRule?

Upvotes: 9

Views: 2962

Answers (1)

user3960875
user3960875

Reputation: 1005

Got it working by initiating PostgreSQLContainer as singleton.

    public static final PostgreSQLContainer postgres = new PostgreSQLContainer();
    static {
        postgres.start();
    }

    @ClassRule
    public final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
            ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
            ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
    );

Upvotes: 10

Related Questions