Search code examples
scalatestingscalatest

ScalaTest: BeforeAndAfter not running


I am trying to learn how to use fixture setup and teardown in ScalaTest. One example I have been trying is the following:

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

The trouble with this is that neither of the before or after blocks are being executed at all. I feel I have followed the instructions in the project docs perfectly - what am I doing wrong?


Solution

  • It turns out I had to add explicit override modifiers to before and after:

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

    However, it should be noted that there most likely is something wrong with my environment, not TestScala. I have not seen anyone else having this issue.