首页 > 解决方案 > 如何使用扩展 BeforeAfterAll 的特征来堆叠行为

问题描述

我的情况是,我有 2 个扩展 BeforeAfterAll 的特征,为集成测试执行不同的操作:一个管理数据库,另一个管理文件系统。例如:

trait DBSpecification extends BeforeAfterAll {

  override def beforeAll() = {
    println("DB -> BeforeAll")
  }

  override def afterAll() = {
    println("DB -> AfterAll")
  }
}

trait FileSystemSpecification extends BeforeAfterAll {

  override def beforeAll() = {
    println("FileSystem -> BeforeAll")
  }

  override def afterAll() = {
    println("FileSystem -> AfterAll")
  }
}

class MyTest extends Specification with DBSpecification with FileSystemSpecification {

  "some test" in {
    1 ==== 1
  }

}

如果我这样做,则只执行最后一个特征的打印,在本例中为 FileSystemSpecification。如果我尝试super从特征调用,我开始遇到一些编译问题。我已经尝试了很多方法,但无法找出解决方案。

ScalaTest 在其文档中有一些示例,但找不到使用 Specs2 的方法。

有任何想法吗?

标签: specs2

解决方案


是的,特质并不是构成行为的最佳选择。这是执行此操作的样板方法:

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

trait DBSpecification extends BeforeAfterAll {

  def beforeAll() = {
    println("DB -> BeforeAll")
  }

  def afterAll() = {
    println("DB -> AfterAll")
  }
}

trait FileSystemSpecification extends BeforeAfterAll {

  def beforeAll() = {
    println("FileSystem -> BeforeAll")
  }

  def afterAll() = {
    println("FileSystem -> AfterAll")
  }
}

trait FileSystemDBSpecification extends DBSpecification with FileSystemSpecification {
  override def beforeAll() = {
    super[DBSpecification].beforeAll()
    super[FileSystemSpecification].beforeAll()
  }

  override def afterAll() = {
    super[DBSpecification].afterAll()
    super[FileSystemSpecification].afterAll()
  }
}

class MyTestSpec extends Specification with FileSystemDBSpecification {

  "some test" in {
    1 ==== 1
  }

}

推荐阅读