Thursday, October 26, 2017

Don't Await when using AsyncFlatSpec in ScalaTest!


There is a subtle behavior to be aware of if you use the scala.concurrent Await in an AsyncFlatSpec. The Scaladoc of Future.apply shows that it requires an implicit ExecutionContext

def apply[T](body: =>T)(implicit execctx: ExecutionContext)

The problem is
ScalaTest will provide one for you and it is single-threaded, so it will block on Await.

For example the following never gets past Await

val f = Future(1)
Await.result(f, Duration.Inf)

This can be solved with

val f = Future(1)(aDifferentExecutionContext)
Await.result(f, Duration.Inf)

But the better approach is not to use Await at all in a AsyncFlatSpec because when using
AsyncFlatSpec you can return Future[Assertion], allowing ScalaTest will resolve the Future.

No comments:

Post a Comment