2014-09-11 63 views
2

我想了解如何在ScalaTest中使用fixture setup和teardown。我一直在尝试的一个例子如下:ScalaTest:BeforeAndAfter未运行

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() 
    } 
    } 
} 

这样做的麻烦在于根本没有执行前或后的块。我觉得我完全按照项目文档中的说明 - 我做错了什么?

+0

你可以添加ScalaTest导入代码以上?我认为它应该工作。 – colinjwebb 2014-09-11 06:37:46

+0

@colinjwebb,是,他们已被添加 – csvan 2014-09-11 09:12:04

回答

0

原来我不得不明确override修饰符添加到之前和之后:

override def before: Any = println("Doing before") 

override def after: Any = println("Doing after") 

然而,应该指出,最有可能是错误的东西与我的环境,不TestScala。我还没有看到任何其他人有这个问题。

1

我想你的榜样,它精致运行:

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 

然而,鉴于大约需要说“超越高清”我你对此有何评论想我知道发生了什么事。我认为你的IDE可能已经完成了BeforeAndAfterEach的代码,即使你想要BeforeAndAfter。所以你在BeforeAndAfterEach中混合使用,确实需要:override def before ...“但是看到BeforeAndAfter的文档。你可以仔细检查一下,看看是否是这个问题吗?