2

我正在尝试使用 specs2 在 Scala 中运行一些测试,但是我遇到了一些未执行的测试用例的问题。

这是一个最小的例子来说明我的问题。

BaseSpec.scala

package foo

import org.specs2.mutable._

trait BaseSpec extends Specification {
  println("global init")
  trait BeforeAfterScope extends BeforeAfter {
    def before = println("before")
    def after = println("after")
  }
}

FooSpec.scala

package foo

import org.specs2.mutable._

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in new BeforeAfterScope {
      "should fail" in {
        true must beFalse
      }
    }
  }
}

我希望测试失败,但是嵌套in语句中的“应该失败”的情况似乎没有被执行。

如果我删除嵌套in语句或BeforeAfterScope,测试行为正确,所以我想我遗漏了一些东西,但我没有设法在文档中找到它。

[编辑]

在我的用例中,我目前正在方法中填充数据库并在before方法中清理它after。但是,我希望能够有几个测试用例,而无需在每个测试用例之间再次清理和填充数据库。这样做的正确方法是什么?

4

1 回答 1

11

必须在您创建示例的确切位置创建范围:

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in new BeforeAfterScope {
        true must beFalse
      }
    }
  }
}

[更新:specs2 3.x 的 10-12-2015]

请注意,如果您不需要从 trait 继承值,那么在其中扩展和定义and方法BeforeAfterScope实际上更简单。BaseSpecorg.specs2.specification.BeforeAfterEachbeforeafter

另一方面,如果您想在所有示例之前和之后进行一些设置/拆卸,则您需要该BeforeAfterAll特征。这是使用这两个特征的规范:

import org.specs2.specification.{BeforeAfterAll, BeforeAfterEach}

trait BaseSpec extends Specification with BeforeAfterAll with BeforeAfterEach {
  def beforeAll = println("before all examples")
  def afterAll = println("after all examples")

  def before = println("before each example")
  def after = println("after each example")
}

class FooSpec extends BaseSpec {
  "foo" should {
    "run specs" in {
      "should fail" in {
        true must beFalse
      }
    }
  }
}

这种方法记录在这里

于 2013-11-04T03:33:12.160 回答