Search code examples
scalascalatest

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 :

  • The before/afterAll do execute
  • The before/after do not

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


Solution

  • 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)