与Testcontainers Dropwizard集成测试
问题描述:
我试图对dockered数据库运行dropwizard的集成测试。与Testcontainers Dropwizard集成测试
我已经试过:
@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())
);
我得到Caused by: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
链接这些结合在一起无法正常工作或
@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())
));
最后这个工程,但据我所知它运行的每个测试的新DropwizardAppRule,这是不好 ...
@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())
);
那么,如何链中的规则,使得PostgreSQLContainer是首先启动并且容器在创建DropwizardAppRule之前已经启动?
答
通过启动PostgreSQLContainer作为单例来实现它。
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())
);