Search code examples
asynchronousscalatest

Is it possible to control execution of Scalatest's async test cases?


I am using ScalaTest's AsyncFlatSpec style. Is there any way I can ensure Second and Third test case only starts execution once First is completed?

Here's the code sample :-

class SomeAsyncSpec extends AsyncFlatSpec with Matchers {

        var mutableVariable = 0

        "First test case" should "perform foo asynchronously" in {
            println("First TEST CASE")
            performFooFutureCall(mutableVariable)
            //assert something
         }

         "Second test case" should "perform bar asynchronously" in {
            println("Second TEST CASE")
            performBarFutureCall(mutableVariable)
            //assert something
         }

         "Third test case" should "perform baz asynchronously" in {
            println("Second TEST CASE")
            performBazFutureCall(mutableVariable)
            //assert something
         }

      }

Solution

  • From the code it's obvious that the reason to execute tests in this suite one after another is to not affect shared mutable state.

    In that case it'll help from the line on AsyncFlatSpec's documentation :-

    https://github.com/scalatest/scalatest/blob/78e506537ed06d4438e1d365e18c160d46d2bf18/scalatest/src/main/scala/org/scalatest/AsyncFlatSpec.scala#L233

    Because ScalaTest's default execution context on the JVM confines execution of Future transformations * and call backs to a single thread, you need not (by default) worry about synchronizing access to mutable state * in your asynchronous-style tests.

    Have a look at documentation from the link provided for more info.