WestCoastProjects
WestCoastProjects

Reputation: 63201

When do before() and after() get invoked within a ScalaTest class with BeforeAndAfter trait

Consider the following minimal viable self contained testcase for BeforeAndAfter and BeforeAndAfterAll:

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuite}

class BeforeAndAfterTestTest extends FunSuite with BeforeAndAfter with BeforeAndAfterAll {

  override protected def beforeAll(): Unit = println("beforeAll")

  override protected def afterAll(): Unit = println("afterAll")

  override protected def before(fun: => Any)(implicit pos: Position): Unit = {
    println("before")
  }

  override protected def after(fun: => Any)(implicit pos: Position): Unit = {
    println("after")
  }

  test("hello1") { println("hello1") }

  test("hello2") { println("hello2") }
}

The result of running this through scalatest is:

enter image description here

So :

What is needed to have the before and after methods get invoked?

Upvotes: 2

Views: 7786

Answers (1)

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

You are supposed to call before and after, not override them:

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuite}

class BeforeAndAfterTestTest extends FunSuite with BeforeAndAfter with BeforeAndAfterAll {

  override protected def beforeAll(): Unit = println("beforeAll")

  override protected def afterAll(): Unit = println("afterAll")

  before {
    println("before")
  }

  after {
    println("after")
  }

  test("hello1") { println("hello1") }

  test("hello2") { println("hello2") }
}

See the documentation here

If you want overrideable methods, you should use BeforeAndAfterEach, not BeforeAndAfter (doc)

Upvotes: 8

Related Questions