1

我实现了 specs2 规范,看起来像这样:

class MySpec extends Specification {

  "My database query" should {

    "return some results " in {
      val conn = createJdbcConn()

      try {
        // matcher here...
      } finally {
        conn.close()
      }
    }
}

在我所有的测试用例中都重复了这个丑陋的样板。我必须为每个in.

在这种情况下,Specs2 关闭资源的惯用方式是什么 - 可能使用After(or BeforeAfter) 特征正确关闭连接?

4

2 回答 2

2

另一种选择是使用FixtureExample2.0 中引入的特征,以避免使用变量:

import org.specs2._
import specification._
import execute._

trait DbFixture extends FixtureExample[JdbcConnection] {
  // type alias for more concise code
  type DBC = JdbcConnection

  /**
   * open the connection, call the code, close the connection
   */
  def fixture[R : AsResult](f: JdbcConnection => R): Result = {
    val connection = createJdbcConnection

    try     AsResult(f(connection))
    finally connection.close
  }
}

class MySpec extends Specification with DbFixture {
  "My database query" should {
    "return some results" in { connection: DBC =>
       // do something with the connection
       success
    }
  }
}
于 2013-08-23T00:39:38.097 回答
1

使用 trait 可能是最简单的,然后需要数据库连接的测试可以扩展 trait(我不喜欢var,但这是最简单的方法):

  trait DbTestLifeCycle extends BeforeAfterExample {

    var dbConn:Option[YourDbConnection] = None

    protected def before: Any = {
      dbConn = Option(createJdbcConn())
    }

    protected def after: Any = {
      dbConn.map(_.close())
    }
  }

所以你的测试看起来像这样:

  class MySpec extends Specification with DbTestLifeCycle {

    "My database query" should {

      "return some results " in {
        dbConn.map(conn => //do something in the db)
        // matcher here...
      }
    }
  }
于 2013-08-22T17:19:08.750 回答