2

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

即,设置:

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

拆除:

actorRef ! PoisonPill

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

4

2 回答 2

3

AroundOutside 为了您的信息,您可以使用隐式上下文在 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
  }
}
于 2013-04-26T00:43:46.403 回答
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

于 2013-04-25T00:41:57.397 回答