我实现了看起来像这样的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
)特性来正确关闭连接?
答案 0 :(得分:2)
另一种选择是使用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
}
}
}
答案 1 :(得分:1)
使用特征可能最简单,然后需要数据库连接的测试可以扩展特性(我对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...
}
}
}