scalaTest:在 org.scalatest.Status 类型的特征 WordSpecLike 中运行的方法需要“抽象覆盖”修饰符

Raj*_*jan 3 scala akka scalatest

我正在尝试为 Akka Actor 编写单元测试。

下面是单元测试代码

import org.scalatest._
import akka.testkit.{TestKit, ImplicitSender, TestActors}
import akka.actor.ActorSystem

class PipFilterTest 
extends TestKit(ActorSystem("testSystem")) 
   with BeforeAndAfterAll 
   with ImplicitSender 
   with WordSpecLike {

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  "PipeFilter Actor" must {
    "send  messages if it passes the filter criteria" in {
      //test code
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行测试代码时,出现以下错误 -

sbt:chapter8_structuralPatterns> test
[info] Compiling 1 Scala source to /rajkumar_natarajans_directory/projectName/target/scala-2.12/test-classes ...
[error] /rajkumar_natarajans_directory/projectName/src/test/scala/PipeFilterTest.scala:13:7: overriding method run in trait BeforeAndAfterAll of type (testName: Option[String], args: org.scalatest.Args)org.scalatest.Status;
[error]  method run in trait WordSpecLike of type (testName: Option[String], args: org.scalatest.Args)org.scalatest.Status needs `abstract override' modifiers
[error] class PipFilterTest extends TestKit(ActorSystem("testSystem")) with StopSystemAfterAll with ImplicitSender with WordSpecLike {
[error]       ^
[error] one error found
[error] (Test / compileIncremental) Compilation failed
Run Code Online (Sandbox Code Playgroud)

当我删除with BeforeAndAfterAllandbeforeAllafterAll方法时,测试运行良好。但是我需要这些来设置测试演员。知道为什么我会收到这些错误。

版本信息:

ScalaTest 3.0.5

阿卡 2.5.11

斯卡拉 2.12.4

And*_*kin 5

此处使用 scalac 2.12.4、akka 2.5.11、scalaTest 3.0.5 编译并运行:

import org.scalatest._
import akka.testkit.{TestKit, ImplicitSender, TestActors}
import akka.actor.ActorSystem

class PipFilterTest 
extends TestKit(ActorSystem("testSystem")) 
   with WordSpecLike
   with ImplicitSender 
   with BeforeAndAfterAll {

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  "PipeFilter Actor" must {
    "send  messages if it passes the filter criteria" in {
      //test code
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

原因是:

  • WordSpecLike 有一个具体的实现 run
  • 如果基类或前面的特征之一已经实现,则只能混合使用 BeforeAndAfterAll run

如果你交换WordSpecLikeand BeforeAndAfterAll,那么编译器认为你想要 mixin WordSpecLike,但BeforeAndAfterAll没有什么可依赖的,因为在它之前没有实现 trait run,因此整个编译失败。

这实际上非常直观:runofBeforeAndAfterAll应该看起来像这样:

abstract override def run(): CrazyScalatestResultType = {
  beforeAll()
  super.run()
  afterAll()
}
Run Code Online (Sandbox Code Playgroud)

如果没有super那个实现run,那么BeforeAndAfterAll也不能正常运行。

要点:mixin 的顺序很重要。

可能相关的链接:Scala's Stackable Trait Pattern