在Play和Squeryl测试中命名的数据库给出了错误

时间:2013-04-24 17:51:38

标签: scala playframework-2.0 squeryl

我按照this link“测试模型”部分在PlaySqueryl中编写测试。但我使用的是命名数据库“test”而不是“default”。以下代码不起作用

import models.{AppDB, Bar}

import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

import org.squeryl.PrimitiveTypeMode.inTransaction

import play.api.test._
import play.api.test.Helpers._

class BarSpec extends FlatSpec with ShouldMatchers {

  "A Bar" should "be creatable" in {
    running(FakeApplication(additionalConfiguration = inMemoryDatabase("test"))) {
      inTransaction {
        val bar = AppDB.barTable insert Bar(Some("foo"))
        bar.id should not equal(0)
      }
    }
  }

}

我收到错误说:

[info] BarSpec:
[info] A Bar 
[info] - should be creatable *** FAILED ***
[info]   com.typesafe.config.ConfigException$BadPath: path parameter: Invalid path ' - could not find datasource for default': Token not allowed in path expression: '-' (you can double-quote this token if you really want it here)
[info]   at com.typesafe.config.impl.Parser.parsePathExpression(Parser.java:881)
[info]   at com.typesafe.config.impl.Parser.parsePath(Parser.java:921)
[info]   at com.typesafe.config.impl.Path.newPath(Path.java:206)
[info]   at com.typesafe.config.impl.SimpleConfig.hasPath(SimpleConfig.java:70)
[info]   at play.api.Configuration.reportError(Configuration.scala:549)
[info]   at play.api.db.BoneCPApi.play$api$db$BoneCPApi$$error(DB.scala:274)
[info]   at play.api.db.BoneCPApi$$anonfun$getDataSource$5.apply(DB.scala:413)
[info]   at play.api.db.BoneCPApi$$anonfun$getDataSource$5.apply(DB.scala:413)
[info]   at scala.Option.getOrElse(Option.scala:108)
[info]   at play.api.db.BoneCPApi.getDataSource(DB.scala:413)
[info]   ...
[error] Failed: : Total 5, Failed 3, Errors 0, Passed 2, Skipped 0
[error] Failed tests:
[error]     DataSourceTest
[error]     BarSpec
java.lang.RuntimeException: Tests unsuccessful

我想我不能在这里直接使用inTransaction。但是当我使用非“默认”数据库名称时,我该怎么做才能使测试用例通过?

谢谢。

1 个答案:

答案 0 :(得分:0)

您只需为多个数据库设置连接,例如:

package models

import org.squeryl.adapters.{H2Adapter}
import org.squeryl.Session
import play.api.Application
import play.api.db.DB


object TestConn {

  def test_session(app : Application) = Session.create( DB.getConnection("test")(app), new H2Adapter)

}

然后在你的BarSpec:

 .....
    "A Bar" should "be creatable" in {
        running(FakeApplication()) {
          transaction(TestConn.test_session(current)){
            val bar = AppDB.barTable insert Bar(Some("foo"))
            bar.id should not equal(0)
          }
        }
      } 
   .....

请注意,对于这些情况,您可能在数据库架构中有conf / evaluatetions / test目录。