数据库事务

时间:2015-06-15 07:30:46

标签: specs2

我正在将我的应用程序从Specs2 2.3.12更新为3.6.1,并且无法更新在事务中包装我们的单元测试的类。

2.3.12类:

class DbTx extends AroundOutside[Session] {
  var session: Option[Session] = None
  def around[T : AsResult](t: => T) = {
    Db.withTransaction { implicit s =>
      session = Some(s)
      val result = AsResult(t)
      s.rollback()
      result
    }
  }
  def outside: Session = session.get
}

其用法:

"my unit test" in (new DbTx).apply { implicit session: Session =>
  ...
}

我在3.6.1

中尝试过的内容
class DbTx extends ForEach[Session] {
  var session: Option[Session] = None
  def foreach[T : AsResult](t: Session => T) = {
    Db.withTransaction { implicit s =>
      session = Some(s)
      val result = AsResult(t)
      s.rollback()
      result
    }
  }
}

其用法:

"my unit test" in (new DbTx).foreach { implicit session: Session =>
  ...
}

但这似乎在第6行和第6行之间产生无限循环。该街区的4个。

我也尝试了

class DbTx extends Around {
  def around[T: AsResult](t: => T): Result = {
    super.around {
      Db.withTransaction { implicit s: Session =>
        val result = AsResult(t)
        s.rollback()
        result
      }
    }
  }
}

其用法:

"my unit test" in (new DbTx).around { implicit session: Session =>
  ...
}

但结果是

could not find implicit value for evidence parameter of type AsResult[Session => MatchResult[ ... ]]

我也尝试了

class DbTx extends Fixture[Session] {
  def apply[T: AsResult](t: Session => T): Result = {
    Db.withTransaction { implicit s: Session =>
      val result = AsResult(t)
      s.rollback()
      result
    }
  }
}

其用法:

"my unit test" in (new DbTx) { implicit session: Session =>
  ...
}

导致

could not find implicit value for evidence parameter of type AsResult[Session => T]

修改

我也在使用这段代码进行无限循环:

import org.specs2.execute.AsResult
import org.specs2.mutable.Specification
import org.specs2.specification.ForEach

class DbTxSpec extends Specification with ForEach[Session] {
  def foreach[T: AsResult](t: Session => T) = {
    Db.withTransaction { implicit s =>  // infinite loop between here
      try AsResult(t)                   // and here
      finally s.rollback()
    }
  }

  "my unit test" in { implicit session: Session =>
    true must beTrue
  }
}

1 个答案:

答案 0 :(得分:1)

如果您想要传递Session,您需要使用您的规范扩展ForEach特征,而不是特殊对象。类似的东西:

class DbTxSpec extends Specification with ForEach[Session] {
  var session: Option[Session] = None

  def foreach[T : AsResult](t: Session => T) = {
    Db.withTransaction { implicit s =>
      session = Some(s)
      try AsResult(t(session))
      finally s.rollback()
    }
  }

  "my unit test" in { implicit session: Session =>
    ...
  }
}