我希望能够运行Play 2 Scala应用程序的单元测试,并使用与生产环境中相同的数据库设置:Slick和Postgres。但以下代码在第二个测试时失败,报错为“java.sql.SQLException: Attempting to obtain a connection from a pool that has already been shutdown.”。
package controllers
import org.specs2.mutable._
import play.api.db.DB
import play.api.Play.current
import play.api.test._
import play.api.test.Helpers._
import scala.slick.driver.PostgresDriver.simple._
class BogusTest extends Specification {
def postgresDatabase(name: String = "default",
options: Map[String, String] = Map.empty): Map[String, String] =
Map(
"db.test.driver" -> "org.postgresql.Driver",
"db.test.user" -> "postgres",
"db.test.password" -> "blah",
"db.test.url" -> "jdbc:postgresql://localhost/blah"
)
def fakeApp[T](block: => T): T =
running(FakeApplication(additionalConfiguration =
postgresDatabase("test") ++ Map("evolutionplugin" -> "disabled"))) {
def database = Database.forDataSource(DB.getDataSource("test"))
database.withSession { implicit s: Session => block }
}
"Fire 1" should {
"do something" in fakeApp {
success
}
}
"Fire 2" should {
"do something else" in fakeApp {
success
}
}
}
我这样运行测试:
$ play -Dconfig.file=`pwd`/conf/dev.conf "test-only controllers.BogusTest"
还有两个谜团:
1)所有测试都运行了,即使我只要求运行BogusTest
2)始终使用application.conf而不是def.conf,并且驱动程序信息来自application.conf而不是在代码中配置的信息。
in{ running(fakeApp) {Database.forDataSource(DB.getDataSource()) withSession {}} }
中包装,也会出现这个异常。 - Meredith