Question

TLDR; In a ScalaTest spec that mixes in both BeforeAndAfterAll and ParallelTestExecution, afterAll() is being called after each test, then again after all of them. I only want the after all behaviour.

I have a ScalaTest spec like this:

class TestSpec extends fixture.FunSpec with ShouldMatchers with BeforeAndAfter with BeforeAndAfterAll with ParallelTestExecution {
   override def afterAll() = {
      println("afterAll")
   }

   describe("something") {
      it("should foo") {
         println("foo")
      }

      it("should bar") {
         println("bar")
      }
   }
}

The two tests want to share a fixture, then afterAll() should clean up the fixture. I've omitted the details of the fixture code as immaterial to this question.

Here's the output of my test:

foo
afterAll
bar
afterAll
afterAll

So afterAll() is being called after each test, then again after all of them. I only want it to be called after all tests.

Does anyone know why afterAll() is behaving like this?

Update

If I don't mix in ParallelTestExecution, my test behaves properly:

foo
bar
afterAll

Unfortunately, I actually want ParallelTestExecution. Is there any way to have my cake and eat it too?

Was it helpful?

Solution

That is a normal behavior since, to reduce the risk of concurrency clashes and bugs, ParallelTestExecution runs each test in its own instance of the Test class. Each one of your tests will be ran as a separate instance of TestSpec, this results in beforeAll and afterAll being executed for each instance.

However you can work around this (in order to get one beforeAll and one afterAll executed for all) using nested suites, see this question for more details.

OTHER TIPS

From the horse's mouth: https://stackoverflow.com/a/15731847/89509

Basically each test case will run as its own instance, which will each call afterAll once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top