0

我写了一个简单的 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$ 
4

1 回答 1

1

我在这里看到两个问题:

  1. result不是 Specs2 的有效“结果”,您需要使用 Specs2 的await功能阻止直到Future完成;

  2. db.run(people.schema.create)在 的构造函数中运行的PeopleDAO,你真的应该把它包装在一个Await.result中,以确保它在你开始运行测试之前已经准备好。

于 2015-06-26T20:33:14.513 回答