gpt4 book ai didi

Dropwizard 与 Testcontainers 的集成测试

转载 作者:行者123 更新时间:2023-12-03 09:50:03 27 4
gpt4 key购买 nike

我正在尝试针对 dockered 数据库运行 dropwizard 的集成测试。

  • Dropwizard
  • Testcontainers

  • 我试过的:
    @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())
    );

    那么如何在创建 DropwizardAppRule 之前链接规则,以便首先启动 PostgreSQLContainer 并启动容器?

    最佳答案

    通过将 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())
    );

    关于Dropwizard 与 Testcontainers 的集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096498/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com