给出如下代码:
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”之后,以及“在”方法之后
即使测试本身失败也要执行吗?
最佳答案
如果您使用的是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
方法用于包装要通过before
和after
执行的代码。同样,如果您向示例之一添加错误,您将看到始终执行“之后”代码。PS:
pp
是一种实用程序方法,类似于println
,可在执行期间在终端中显示某些内容。与println相比,优点是它返回其参数,因此您可以编写1.pp must_== 1
关于scala - Specs2和@ Before/@ After之后的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14295048/