igx
igx

Reputation: 4231

How to test list of futures in Scala

I would like to test a method (using ScalaTest) that accepts a List of values and updates them in a database, returning a Future for each value indicating success of the update. Is there an idiomatic way to verify that all values are persisted in the DB? How can I know when all Futures returned from the method are completed?

trait Result
case object A extends Result
case object B extends Result

def addToDB(i: String): Future[Result]

def persistUsers(users: List[String]): List[Future[Result]] = {
  users.map(addToDB)
}

I tried something like this (works) but is there a better way ?

"should update list " in {
  val users = List("a","b","c")

  persistUsers(users)

  Thread.sleep(1000)

  whenReady(db.find("a")) { result => result shouldEqual A }
  .
  .
  .

}

Upvotes: 3

Views: 1091

Answers (1)

David
David

Reputation: 96

So you want to await for a list of Futures, you have several options (I don't know if ScalaTest has a whenReady for a list of Futures), one of them is using Future.sequence(futureList) to create a Future[List[A]]

val futures = persistUsers(users)

whenReady(Future.sequence(futures)){result => result shouldEqual users}

Upvotes: 6

Related Questions