我正在尝试学习如何在 ScalaTest 中使用固定装置设置和拆卸。我一直在尝试的一个例子如下:
import org.scalatest._
import scala.collection.mutable
class SampleTest extends FlatSpec with BeforeAndAfter with Matchers{
before {
// Setup code
}
after {
// Teardown code
}
"A Stack" should "pop values in last-in-first-out order" in {
val stack = new mutable.Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() should be (2)
stack.pop() should be (1)
}
it should "throw NoSuchElementException if an empty stack is popped" in {
val emptyStack = new mutable.Stack[Int]
a [NoSuchElementException] should be thrownBy {
emptyStack.pop()
}
}
}
这样做的问题是 before 或 after 块根本没有被执行。我觉得我完全遵循了项目文档中的说明 - 我做错了什么?
我尝试了你的示例,它运行良好:
import org.scalatest._
import scala.collection.mutable
class SampleSpec extends FlatSpec with BeforeAndAfter with Matchers{
before {
info("Setup code")
}
after {
info("Teardown code")
}
"A Stack" should "pop values in last-in-first-out order" in {
val stack = new mutable.Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() should be (2)
stack.pop() should be (1)
}
it should "throw NoSuchElementException if an empty stack is popped" in {
val emptyStack = new mutable.Stack[Int]
a [NoSuchElementException] should be thrownBy {
emptyStack.pop()
}
}
}
将其粘贴到 REPL 中将为您提供:
scala> new SampleSpec execute
SampleSpec:
A Stack
+ Setup code
- should pop values in last-in-first-out order
+ Teardown code
+ Setup code
- should throw NoSuchElementException if an empty stack is popped
+ Teardown code
但是,鉴于您评论需要说“覆盖 def”,我想我知道发生了什么。我认为您的 IDE 可能已经完成了 BeforeAndAfterEach 的代码,即使您想要 BeforeAndAfter。所以你混合了 BeforeAndAfterEach,这确实需要 :override def before...”,但是正在查看 BeforeAndAfter 的文档。你能仔细检查一下,看看这是否是问题所在?
事实证明我必须在之前和之后添加显式覆盖修饰符:
override def before: Any = println("Doing before")
override def after: Any = println("Doing after")
但是,应该注意的是,很可能是我的环境有问题,而不是TestScala。我还没有看到其他人遇到这个问题。
也可以是,如果没有任何错误编写的测试,例如注释了像
"A Stack" should "pop values in last-in-first-out order" in { blah blah blah the test code }
这样的测试,那么之前和之后将永远不会被调用