我正在尝试编写一个具有Scope传入值的可变Spec。我还需要在每次测试运行后进行一些清理。在文档之后,我尝试使用Outside结合After,但结果好坏参与。
第五个例子是正确的方法还是我遗漏了一些基本的东西?
import org.specs2.mutable.{After, Specification}
import org.specs2.specification.Outside
class ExampleSpec extends Specification {
"Tests using Outside and After" >> {
"#1 doesn't run the after" in c1() {
(m: String) => {
println("Running test 1.")
success
}
}
"#2 doesn't actually run the test" in new c2() {
(m: String) => {
println("Running test 2.")
failure
}
}
"#3 doesn't run the after" in (new t3{}) {
(m: String) => {
println("Running test 3.")
success
}
}
"#4 doesn't actually run the test" in new t4 {
(m: String) => {
println("Running test 4.")
failure
}
}
"#5 works, but is it the right way?" in new t5 {
val sessionKey = outside // The test would have to call outside?
println("Running test 5.")
success
}
}
trait common extends Outside[String] with After {
def name: String
def outside = "Used by the real test."
def after = println("After for " + name)
}
case class c1() extends common { def name = "c1" }
case class c2() extends common { def name = "c2" }
trait t3 extends common { def name = "t3" }
trait t4 extends common { def name = "t4" }
trait t5 extends common { def name = "t5" }
}
这给出了以下输出:
Running test 1.
After for c2
Running test 3.
After for t4
Running test 5.
After for t5
[info] ExampleSpec
[info]
[info] Tests using Outside and After
[info] + #1 doesn't run the after
[info] + #2 doesn't actually run the test
[info] + #3 doesn't run the after
[info] + #4 doesn't actually run the test
[info] + #5 works, but is it the right way?
[info]
[info] Total for specification ExampleSpec
[info] Finished in 19 ms
[info] 5 examples, 0 failure, 0 error
注意:根据Eric对Question 21154941的评论,我发现测试1和2不是正确的方法。我把它们放在这里是详尽无遗的,因为在其他时候,你可以使用case类来进行上下文/变量隔离。
答案 0 :(得分:0)
在您的情况下,最简单的方法是使用org.specs2.specification.FixtureExample
特征:
class ExampleSpec extends Specification with FixtureExample[F] {
"Tests using a fixture" >> {
"you can use the fixture values" in { f: F =>
println("Running test 1 with "+f.sessionKey)
success
}
"there is cleanup after each example" in { f: F =>
success
}
}
def fixture[R : AsResult](f: F => R): Result = {
try AsResult(f(F()))
finally cleanup
}
def cleanup = println("cleanup")
}
case class F(sessionKey: String = "key")