在所有测试运行之前仅初始化一次值

时间:2017-05-18 15:52:29

标签: scala unit-testing sbt specs2

我想在所有测试运行之前仅初始化值

现在值insertDbScheme在每个测试中创建方案,如果可以只运行一次。从sbt任务不适合插入方案

我有两个测试

TEST1:

class Test1 extends Specification with InsertDbScheme {

  "test" in {
    insertDbScheme
    // some code
    ok
  }
}

TEST2:

class Test2 extends Specification with InsertDbScheme {

  "test" in {
    insertDbScheme
    // some code
    ok
  }
}

和将方案插入数据库的基本特征

trait InsertDbScheme {

  lazy val insertDbScheme = {
    println("insert scheme to database")
  }
}

运行测试的结果

insert scheme to database
insert scheme to database
[info] Test1
[info] 
[info] + test
[info] 
[info] 
[info] Total for specification Test1
[info] Finished in 152 ms
[info] 1 example, 0 failure, 0 error
[info] 
[info] Test2
[info] 
[info] + test
[info] 
[info] 
[info] Total for specification Test2
[info] Finished in 152 ms
[info] 1 example, 0 failure, 0 error
[info] 
[info] ScalaCheck
[info] Passed: Total 0, Failed 0, Errors 0, Passed 0
[info] Passed: Total 2, Failed 0, Errors 0, Passed 2
[success] Total time: 12 s, completed May 18, 2017 6:35:21 PM

2 个答案:

答案 0 :(得分:1)

您可以使用object确保lazy val仅实例化一次:

trait InsertDbScheme {
  import InsertDbScheme._
  lazy val insertDbScheme = insertDbSchemeOnce
}

object InsertDbScheme { 
  lazy val insertDbSchemeOnce = {
    println("insert scheme to database")
  }
}

答案 1 :(得分:0)

最简单的方法是在InsertDbScheme对象中使用变量:

trait InsertDbScheme {

  def insertDbScheme = synchronized {
    if (!InsertDbScheme.done) {
      println("insert scheme to database")
      InsertDbScheme.done = true
    }        
  }
}

object InsertDbScheme {
  var done = false
}