使用Akka TestKit和Specs2进行测试

6

我正在尝试使用Akka的TestKit编写specs2测试。我遇到了一个持久性的编译错误,无法解决,希望得到建议。

编译错误如下:

TaskSpec.scala:40: parents of traits may not have parameters
[error]   with akka.testkit.TestKit( ActorSystem( "testsystem", ConfigFactory.parseString( TaskSpec.config ) ) )

根据Akka文档xebia和《Akka实战》的建议,我正在尝试将TestKit整合到specs2 Scope中。这里是我遇到错误的代码片段:

class TaskSpec 
extends Specification 
with AsyncTest
with NoTimeConversions { 

  sequential 

  trait scope 
  extends Scope 
  with TestKit( ActorSystem( "testsystem", ConfigFactory.parseString( TaskSpec.config ) ) ) 
  with AkkaTestSupport {
...

我有以下助手:

我有以下辅助程序:

trait AkkaTestSupport extends After { outer: TestKit =>
  override protected def after: Unit = {
    system.shutdown()
    super.after
  }
}
1个回答

6

以下是您可以做的一件事:

import org.specs2.mutable.SpecificationLike
import org.specs2.specification._

class TestSpec extends Actors { isolated
  "test1" >> ok
  "test2" >> ok
}

abstract class Actors extends 
 TestKit(ActorSystem("testsystem", ConfigFactory.parseString(TaskSpec.config)))
 with SpecificationLike with AfterExample {

  override def map(fs: =>Fragments) = super.map(fs) ^ step(system.shutdown, global = true)

  def after = system.shutdown
}

这样可以避免编译错误,因为TestKit是一个抽象类,只是混合了特征:SpecificationLike 是一个特征(Specification不是),而 AfterExample 是一个特征。

另外,上面的规范以isolated模式运行,这意味着每个示例都会实例化一个全新的TestSpec对象,并且AfterExample特征确保在每个示例之后关闭系统。

最后,map方法被重写为一个特殊的step,以确保为第一个TestSpec实例(声明所有示例的实例)创建的system将被清洗处理。


感谢您的建议。我最终通过将范围更改为类(错过了那个)来解决这个问题,但我正在尝试这种结构。 - dr.
谢谢Eric。你上面指定的步骤中,global=true参数是什么意思? - Leo
“隔离”规范意味着每个示例在其自己的规范类副本中执行,并且所有先于示例的步骤也会执行(因为它们可能对设置上下文很重要)。除非它们被标记为“全局”,在这种情况下,它们仅为整个规范执行一次。 - Eric
更新的解决方案请查看 https://github.com/gangstead/specs2-akka-testkit-demo/blob/master/src/test/scala/MySpec.scala - Synesso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接