【问题标题】:Specs2: Using Outside with AfterSpecs2:在外面使用 After
【发布时间】:2014-05-13 16:40:04
【问题描述】:

我正在尝试编写一个可变规范,该规范具有由 Scope 传入的值。我还需要能够在每次测试运行后进行一些清理。按照文档,我尝试使用 OutsideAfter 组合,但结果好坏参半。

第五个例子是正确的方法还是我错过了一些基本的东西?

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 的 cmets 到 Question 21154941,我意识到测试 1 和 2 不是正确的方法。我把它们放在这里是为了详尽无遗,因为在其他时候,您可以使用案例类进行上下文/变量隔离。

【问题讨论】:

    标签: specs2


    【解决方案1】:

    在您的情况下,最简单的做法是使用 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")
    

    【讨论】:

    • 谢谢,埃里克。这应该让我走上正轨。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多