我写了一个简单的Slick DAO,我正在尝试为DAO编写单元测试
这是我DAO的代码
package tables
import slick.driver.H2Driver.api._
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.Play.current
case class Person(id: Int, firstname: String, lastname: String)
class People(tag: Tag) extends Table[Person] (tag, "PEOPLE") {
def id = column[Int]("PEOPLE_ID", O.PrimaryKey)
def firstname = column[String]("PEOPLE_FIRSTNAME")
def lastname = column[String]("PEOPLE_LASTNAME")
def * = (id, firstname, lastname) <> (Person.tupled, Person.unapply _)
}
object PeopleDAO {
val people = TableQuery[People]
val db = Database.forConfig("h2mem1")
db.run(people.schema.create)
def loadDummyData() {
try {
db.run(people ++= Seq(
Person(1, "test1", "user1"),
Person(2, "test2", "user2"),
Person(3, "test3", "user3")))
} finally db.close
}
def create(input : Person) {
try {
db.run(people ++= Seq(input))
} finally db.close
}
def getAll() {
people.map(x => x)
}
def getById(id: Int) {
people.filter(x => x.id === id)
}
}
这是单元测试
import org.specs2.mutable._
import tables._
class DBOTest extends Specification {
"A DBO " should {
"load test data " in {
val result = PeopleDAO.loadDummyData()
result.map{ x =>
x.foreach { y =>
println(s" number of rows $y")
y equalTo 3
}
}
}
}
}
现在我的代码编译得很好。但是当我通过activator test
运行单元测试时,我得到了神秘的错误消息
[info] Compiling 3 Scala sources to /Users/abhi/ScalaProjects/MyPlay1/target/scala-2.11/test-classes...
[error] /Users/abhi/ScalaProjects/MyPlay1/test/DBOTest.scala:8: type mismatch;
[error] found : => result.type (with underlying type => result.type)
[error] required: ?{def map(x$1: ? >: <error> => <error>): ?}
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error] both method lazyParameter in trait LazyParameters of type [T](value: => T)org.specs2.control.LazyParameter[T]
[error] and method theValue in trait MustExpectations1 of type [T](t: => T)org.specs2.matcher.MustExpectable[T]
[error] are possible conversion functions from => result.type to ?{def map(x$1: ? >: <error> => <error>): ?}
[error] result.map{ x =>
[error] ^
[error] one error found
[error] (test:compileIncremental) Compilation failed
[error] Total time: 5 s, completed Jun 26, 2015 2:50:09 PM
Mohitas-MBP:MyPlay1 abhi$
答案 0 :(得分:1)
我在这里看到两个问题:
result
不是有效的&#34;结果&#34;对于Specs2,您需要使用Specs2的await
功能来阻止此Future
完成;
db.run(people.schema.create)
在PeopleDAO
的构造函数中运行,您应该将其Await.result
包裹起来以确保它在您开始运行之前已准备就绪测试