如何在specs2中为DataTables定义Context

时间:2013-05-08 02:12:54

标签: unit-testing scala specs2

我正在尝试定义一些上下文,以便为每行数据表执行它(在每行上执行断言之前)。

我找到了this示例,但就我而言,我无法弄清楚如何编写完整的测试套件。 我想定义一次上下文并与所有示例共享。 这大致是我所拥有的:

class SomeSuite extends Specification with DataTables {

// TODO: define context somehow???
// val context = new Before { println("BEFORE") }

"test 1" should {
  "do something" in {
    context |
    "col1" | "col2" |
    val1   ! val2   |
    val3   ! val4   |> {
      (a, b) => //some assertion with (a, b)
    }
  }
}
}

我希望在每次断言(a,b)之前,每次都会看到“BEFORE”(共2次)。

我真的很感激任何帮助。

谢谢;)

感谢Eric,这是我的最终代码。我只添加了'隐含',因为许多测试共享了上下文:

class SomeSuite extends Specification with DataTables {

  implicit val context = new Before { def before = println("BEFORE") }

  "test 1" should {
    "do something" in {
      "col1"  | "col2"  |
      val1    ! val2    |
      val3    ! val4    |> { (a, b) => 
        a must_== b // this is wrapped with context
      }
    }
  }
}

1 个答案:

答案 0 :(得分:5)

简单的方法是使用apply

Context方法
class SomeSuite extends Specification with DataTables {

  val context = new Before { def before = println("BEFORE") }

  "test 1" should {
    "do something" in {
      "col1"  | "col2"  |
      val1    ! val2    |
      val3    ! val4    |> { (a, b) => 
        context { a must_== b } 
      }
    }
  }
}