代码之家  ›  专栏  ›  技术社区  ›  user3960875

Dropwizard与Testcontainers的集成测试

  •  8
  • user3960875  · 技术社区  · 7 年前

    我试过的:

    @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首先启动,而container在创建DropwizardAppRule之前已经启动?

    1 回复  |  直到 7 年前
        1
  •  10
  •   user3960875    7 年前

    通过将PostgreSQLContainer初始化为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())
        );