2017-07-14 208 views
1

我試圖對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之前已經啓動?

回答

2

通過啓動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()) 
    );