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

scalaTest:method run in trait WordSpecLike of type org.scalatest.Status needs `abstract override' modifiers

我正在尝试为 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
    }
  }
}

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

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

当我删除 with BeforeAndAfterAllbeforeAll 以及 afterAll 方法时,然后测试 运行 没问题。但我需要这些来设置测试演员。 知道为什么我会收到这些错误。

版本信息:

scalaTest 3.0.5

阿卡 2.5.11

scala 2.12.4

此处使用 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
    }
  }
}

原因是:

  • WordSpecLike 有 run
  • 的具体实现
  • BeforeAndAfterAll 只有在基础 class 或之前的特征之一已经实现时才能混入 run

如果你交换 WordSpecLikeBeforeAndAfterAll,那么编译器认为你想混合 WordSpecLike,但是 BeforeAndAfterAll 就没有什么可依赖的了,因为那里在实现 run 之前没有特征,因此整个编译失败。

这实际上很直观:BeforeAndAfterAllrun 应该看起来像这样:

abstract override def run(): CrazyScalatestResultType = {
  beforeAll()
  super.run()
  afterAll()
}

如果没有实现runsuper,那么BeforeAndAfterAll也无法正常运行。

要点:mixins 的顺序很重要。

可能相关 link:Scala's Stackable Trait Pattern