How to initialize shared variables before parallel test in scalatest

916 views Asked by At

I have scalatest codes like following:

class myTest extends FlatSpec with ParallelTestExecution {  

    val testSuiteId: String = GenerateSomeRandomId() 

    it should "print test id" in { 
        println(testSuiteId)
    } 

    it should "print test id again" in { 
        println(testSuiteId) 
    }
} 

The two tests cannot print the testSuiteId I generate before them. Instead they regenerate the ID and print it. I understand that because of ParallelTestExecution which extends OneInstancePerTest, each test here runs on its own instance and have a copy of the variable "testSuiteId".

But I do want a fixed Id for this test suite and each test case in this suite have access to this fixed it without modifying it. I tried to create the fixed id in BeforeAll{ } but still it didn't work.

How should I achieve what I want?

1

There are 1 answers

1
Joe K On BEST ANSWER

One way to work around it would be to put the shared state in some sort of external object:

object SuiteId {
  lazy val id: String = GenerateSomeRandomId()
}

Admittedly this is very much a hack, and I wouldn't be surprised if scalatest has a way to handle this built-in which I am unaware of.