How to test methods that return Future?

前端 未结 6 2181
时光说笑
时光说笑 2021-02-07 08:25

I\'d like to test a method that returns a Future. My attempts were as follows:

import  org.specs2.mutable.Specification
import scala.concurrent.Exec         


        
6条回答
  •  半阙折子戏
    2021-02-07 08:47

    There is a nice thing for that in specs2 - implicit await method for Future[Result]. If you take advantage of future transformations you can write like this:

    "save notification" in {
      notificationDao.saveNotification(notification) map { writeResult =>
        writeResult.ok must be equalTo (true)
      } await
    }
    

    Future composition comes to the rescue when some data arrangement with async functions is needed:

    "get user notifications" in {
      {
        for {
          _ <- notificationDao.saveNotifications(user1Notifications)
          _ <- notificationDao.saveNotifications(user2Notifications)
          foundUser1Notifications <- notificationDao.getNotifications(user1)
        } yield {
          foundUser1Notifications must be equalTo (user1Notifications)
        }
      } await
    }
    

    Note how we have to use an additional block around for-comprehension to convince compiler. I think it's noisy, so if we turn await method in a function we come up with a nicer syntax:

    def awaiting[T]: Future[MatchResult[T]] => Result = { _.await }
    
    "get user notifications" in awaiting {
      for {
        _ <- notificationDao.saveNotifications(user1Notifications)
        _ <- notificationDao.saveNotifications(user2Notifications)
        foundUser1Notifications <- notificationDao.getNotifications(user1)
      } yield {
        foundUser1Notifications must be equalTo (user1Notifications)
      }
    }
    

提交回复
热议问题