【问题标题】:Specs2 - close JDBC connection after each test caseSpecs2 - 在每个测试用例之后关闭 JDBC 连接
【发布时间】:2013-08-23 08:39:38
【问题描述】:

我实现的 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(或 BeforeAfter)特征来正确关闭连接?

【问题讨论】:

    标签: scala specs2


    【解决方案1】:

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

    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
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      使用 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...
            }
          }
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        相关资源
        最近更新 更多