Specs2和@ Before / @ After-like方法

时间:2013-01-12 15:57:07

标签: scala specs2

给出如下代码:

class RESTAcceptanceTest extends Specification {

  override def is = anonymous ^ signinOAuth

  def anonymous = "Something"       ^ givenSomething ^
                  "must happen"     ^ mustHappen 
  end

  def signinOAuth = "Signin"                ^ givenSignin ^
                    "works as expected"     ^ userExistsInDatabase 
  end

  // rest of object definitions

}

如何确保在/之前执行代码之前和之后相同 在“匿名”“signinOAuth”之后,“after”方法应该 即使测试失败了也要执行?

2 个答案:

答案 0 :(得分:3)

如果你正在使用Given / When / Then步骤,你可以使用Context来控制每个例子之前和之后执行的内容:

import org.specs2._
import specification._

class MySpec extends Specification { def is = 
  "anonymous" ^ 
    "something" ^ something ^
    "must happen" ^ mustHappen ^ endp^
  "OAuth"^ 
    "signing" ^ signing ^
    "works ok" ^ worksOk

  lazy val something: Given[Int] = (s: String) => { s.pp; 1 } 
  lazy val mustHappen: Then[Int] = (i: Int) => (s: String)  => 
    context { s.pp; i must_== 1       }

  lazy val signing:  Given[Int] = (s: String) => { s.pp; 2 }
  lazy val worksOk: Then[Int] = (i: Int) => (s: String) => 
    context { s.pp; i must_== 2 }

  lazy val context = new BeforeAfter {
   def  before = "before".pp
   def after = "after".pp
  }
}

在上面的代码中,apply对象的context方法用于包装要使用beforeafter执行的代码。此外,如果您向其中一个示例添加错误,您将看到始终执行“after”代码。

PS:pp是一种实用方法,如println,用于在执行期间在终端中显示内容。 println的优点是它返回它的参数,因此你可以写1.pp must_== 1

答案 1 :(得分:2)

查看文档:{​​{3}}