application-test.properties

H2 のメモリデータベースに対してすべてのテストを実行する必要があります。これを行う簡単な方法は、src/test/resources/application-test.properties をプロジェクトに追加することです。 application-test.properties でデータソースのプロパティを上書きして H2 を使用するように指定できます。

すべてのテストをメモリデータベースの H2 で実行します。

データベース インスタンスが DB.getDefault() によって自動的に作成されると、Ebean はクラスパスに application-test.properties が存在するかどうかを確認します。見つかった場合、通常はメモリ内の H2 データソースを使用するように指定します。

application-test.properties の例

## Create DB from scratch prior to running tests
ebean.db.ddl.generate=true
ebean.db.ddl.run=true

## Use H2 when running tests
datasource.db.username=sa
datasource.db.password=
datasource.db.databaseUrl=jdbc:h2:mem:tests
datasource.db.databaseDriver=org.h2.Driver

プログラム - loadTestProperties()

DatabaseConfigDatabaseFactory を使用してプログラムでデータベース インスタンスを作成する場合、application-test.properties ファイルが存在する場合に探し出す databaseConfig.loadTestProperties() というメソッドがあります。

@Override
public Database getObject() throws Exception {

  DatabaseConfig config = new DatabaseConfig();
  config.setName("db");
  config.loadFromProperties(properties);
  ...

  // load application-test.properties if present for running tests
  // typically using H2 in memory database
  config.loadTestProperties();

  // set as default and register so that Model can be
  // used if desired for save() and update() etc
  config.setDefaultServer(true);
  config.setRegister(true);

  return DatabaseFactory.create(config);
}