scalaTest:method run in trait WordSpecLike of type org.scalatest.Status 需要 'abstract override' 修饰符



我正在尝试为 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 BeforeAndAfterAllbeforeAllafterAll方法时,测试运行良好。但是我需要这些来设置测试参与者。知道为什么我会收到这些错误。

版本信息:

标量测试 3.0.5

阿卡 2.5.11

斯卡拉 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的具体实现
  • 只有在基类或前面的特征之一已经实现run

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

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

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

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

要点:混合顺序很重要。

可能相关的链接:Scala的可堆叠特征模式

最新更新