将演化应用于 ScalikeJDBC 内存中测试数据库

Applying evolutions to ScalikeJDBC in-memory test DB

我在 Play 中使用 ScalikeJDBC。我想为我的 Specs2 测试将演进应用于内存数据库。

import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAfterAll
import play.api.db.{Database, Databases}
import play.api.db.evolutions.Evolutions
import scalikejdbc.ConnectionPool.DEFAULT_NAME
import scalikejdbc.{ConnectionPool, DataSourceConnectionPool}

import scalikejdbc.{AutoSession, _}

class PaymentRepoSpec extends Specification with BeforeAfterAll {

  private var database: Option[Database] = None

  def beforeAll(): Unit = {
    database = Some(Databases.inMemory(
      name = "payment-repo",
      urlOptions = Map("MODE" -> "PostgreSQL", "DATABASE_TO_UPPER" -> "FALSE"),
      config = Map()
    ))
    database.foreach(Evolutions.applyEvolutions(_))
    database.foreach(db => ConnectionPool.add(DEFAULT_NAME, new DataSourceConnectionPool(db.dataSource)))
  }

  def afterAll(): Unit = {
    database.foreach(Evolutions.cleanupEvolutions(_))
    database.foreach(_.shutdown())
  }

  "fruitcakes" should {
    "be delicious" >> {

      import scalikejdbc._

      DB.readOnly { implicit s =>
        sql"""select id from payments"""
          .map(_.int(1)).list().apply().foreach(println)
      }
      ok
    }
  }
}

这失败了,因为还没有应用进化。

org.h2.jdbc.JdbcSQLException: Table "payments" not found; SQL statement:
select id from payments [42102-192]

application.conf 包括

modules.enabled += "scalikejdbc.PlayModule"
modules.disabled += "play.api.db.DBModule"

进化。default/1.sql包括

CREATE TABLE payments(
    id                  SERIAL PRIMARY KEY,
    source              CHAR(56) NOT NULL,
    destination         CHAR(56) NOT NULL,
    code                VARCHAR(12) NOT NULL,
    issuer              CHAR(56),
    units               NUMERIC NOT NULL,
    received            TIMESTAMP NOT NULL,
    scheduled           TIMESTAMP NOT NULL,
    submitted           TIMESTAMP,
    status              VARCHAR(9) NOT NULL CHECK (status IN ('pending', 'submitted', 'failed', 'succeeded')),
    op_result           VARCHAR(64)
);

(这在 运行 应用程序时有效)

build.sbt 包括

libraryDependencies ++= Seq(
  guice, evolutions, jdbc, specs2 % Test,
  "io.github.synesso" %% "scala-stellar-sdk" % "0.5.1",
  "com.nrinaudo" %% "kantan.csv-generic" % "0.4.0",
  "com.h2database" % "h2" % "1.4.192",
  "org.postgresql" % "postgresql" % "42.2.5",
  "org.scalikejdbc" %% "scalikejdbc" % "3.3.0",
  "org.scalikejdbc" %% "scalikejdbc-config" % "3.3.0",
  "org.scalikejdbc" %% "scalikejdbc-play-initializer" % "2.6.0-scalikejdbc-3.3",
  "org.webjars.npm" % "bulma" % "0.7.2",
  "org.webjars" % "font-awesome" % "5.6.3",
  "org.specs2" %% "specs2-scalacheck" % "4.3.6" % Test
)

我怎样才能测试 运行 针对我的 ScalikeJDBC 数据库的演变?

Databases.inMemory中的参数name必须匹配evolutions下的文件夹。

例如,如果进化在evolutions/default/*.sql,那么你必须调用Databases.inMemory(name="default", db)