【问题标题】:Scalatest or Specs2 - Set up and teardown of variables in tests running in parallelScalatest 或 Specs2 - 在并行运行的测试中设置和拆卸变量
【发布时间】:2013-04-18 14:48:20
【问题描述】:

如果我需要为套件中的每个测试设置一些变量,是否可以在不为每个测试编写套件的情况下以某种方式设置它们并将它们放入测试中?

即设置:

val actorRef = context.actorOf(Props(new MyTestDude))

拆解:

actorRef ! PoisonPill

如果我使用 setup 和 teardown 钩子运行,我需要将 actorref 作为测试类中的一个字段,以便可以从 setup 方法访问它,但是我不能并行运行测试,因为每个人都将共享相同的状态。

【问题讨论】:

    标签: scala tdd bdd scalatest specs2


    【解决方案1】:

    为了您的信息,您可以使用 AroundOutside implicit context 在 specs2 中执行类似的操作:

    import org.specs2._
    import execute._
    import specification._
    
    class s extends mutable.Specification {
      // this context will be used for each example
      implicit def withActor = new AroundOutside[ActorRef] { 
    
        // actor is passed to each example
        val actor = context.actorOf(Props(new MyTestDude)) 
        def outside = actor
    
        // execute the example code
        def around[R : AsResult](r: =>R) = {
          try AsResult(r)
          finally (actor ! PoisonPill)
        }
      }
    
      "My actor rules!" in { actor: ActorRef =>
         actor ! "very important message"
         ok
      }
    }
    

    【讨论】:

      【解决方案2】:

      在 Scalatest 中,所有 Suite 子类都有某种处理方式,具体的套件类在 Scaladoc 中有详细描述。

      这是一个使用 FunSuite 的示例,基于文档。 http://www.artima.com/docs-scalatest-2.0.M5b/#org.scalatest.FunSuite

      class ExampleSuite extends fixture.FunSuite {
      
        case class F(actorRef: ActorRef)
        type FixtureParam = F
      
        def withFixture(test: OneArgTest) {
      
          val actorRef = context.actorOf(Props(new MyTestDude))
          val fixture = F(actorRef)
      
          try {
            withFixture(test.toNoArgTest(fixture)) // "loan" the fixture to the test
          }
          finally {
            actorRef ! PoisonPill
          }
        }
      
        test("My actor rules!") { f =>
          f.actorRef ! "very important message"
          assert( ... )
        }
      }
      

      另外请注意,Akka 有一个用于 ScalaTest 的特殊模块,称为 TestKit,它通常会使测试 actor 变得更加容易。 http://doc.akka.io/docs/akka/snapshot/scala/testing.html

      【讨论】:

      • 非常感谢。我开始阅读 Scala 中的测试,但您仍然比阅读更快地让我得到答案。感谢您的时间和方向。
      • 文档中也有描述,但上面的代码使用了固定装置中的贷款模式,供任何对孤立的清理策略感兴趣的人使用:wiki.scala-lang.org/display/SYGN/Loan
      猜你喜欢
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      相关资源
      最近更新 更多