Search code examples
scalasbtscalatest

Run ScalaTest tests in parallel


Given the following test suite:

class ParallelizeMe extends FunSuite with BeforeAndAfterAll {

  override def beforeAll() = println("before")              
  override def afterAll()  = println("after")               

  test("test 1") {                                          
    println("1a")
    Thread.sleep(3000)                                      
    println("1b")                                           
  }

  test("test 2") {                                          
    println("2a")
    Thread.sleep(1000)                                      
    println("2b")
  }

} 

How can I run the tests (via sbt) in parallel? Ideally, I want the order of execution to produce the following on stdout:

before
1a
2a
2b
1b
after

Solution

  • Use ParallelTestExecution and a -P command-line argument to the Runner to make them run in parallel:

    import org.scalatest.{ParallelTestExecution, BeforeAndAfterAll, FunSuite}
    class ParallelizableSpec extends FunSuite with BeforeAndAfterAll with ParallelTestExecution {
       ...
    }
    

    Note that -P is required. From the source:

    If you include -P on the command line, Runner will pass a Distributor to the Suites you specify with -s. Runner will set up a thread pool to execute any Suites passed to the Distributor's put method in parallel.

    It will also run the tests in isolation, so before and after will be run in each thread. See more in the docs for ParallelTestExecution and Runner.

    In SBT, to use the flag, add this to build.sbt:

    testOptions in Test += Tests.Argument("-P")