如何测试返回Future的方法?

时间:2015-01-02 23:58:25

标签: scala specs2

我想测试一个返回Future的方法。我的尝试如下:

import  org.specs2.mutable.Specification
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

class AsyncWebClientSpec extends Specification{

  "WebClient when downloading images" should {
    "for a valid link return non-zero content " in {
      val testImage = AsyncWebClient.get("https://www.google.cz/images/srpr/logo11ww.png")
      testImage.onComplete { res => 
        res match {
          case Success(image) => image must not have length(0)
          case _ =>
        }
        AsyncWebClient.shutDown
      }
    }
  }
}

除了我无法使这段代码工作之外,我想有一种更好的方法可以用面向Future的匹配器测试期货。

如何在specs2中正确执行?

6 个答案:

答案 0 :(得分:18)

您可以使用Matcher.await方法将Matcher[T]转换为Matcher[Future[T]]

val testImage: Future[String] =
   AsyncWebClient.get("https://www.google.cz/images/srpr/logo11ww.png")  

// you must specify size[String] here to help type inference
testImage must not have size[String](0).await

// you can also specify a number of retries and duration between retries
testImage must not have size[String](0).await(retries = 2, timeout = 2.seconds)

// you might also want to check exceptions in case of a failure
testImage must throwAn[Exception].await

答案 1 :(得分:13)

我花了一段时间才发现这个想法,我想分享一下。我应该阅读发行说明。在specs2 v3.5中,需要使用隐式ExecutionEnv来为将来使用await。这也可以用于将来的转换(即地图),请参阅http://notes.implicit.ly/post/116619383574/specs2-3-5

从那里摘录以供快速参考:

import org.specs2.concurrent.ExecutionEnv

class MySpec extends mutable.Specification {
  "test of a Scala Future" >> { implicit ee: ExecutionEnv =>
    Future(1) must be_>(0).await
  }
}

答案 2 :(得分:6)

在specs2中有一个很好的东西 - await的隐式Future[Result]方法。如果您利用未来的转换,您可以这样写:

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

当需要一些具有异步功能的数据安排时,未来的构成将得到拯救:

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

请注意我们必须使用额外的块来进行理解才能说服编译器。我认为这很吵,所以如果我们在函数中转换await方法,我们会得到一个更好的语法:

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)
  }
}

答案 3 :(得分:3)

onComplete返回Unit,以便代码块立即返回,测试结束后才能执行任何操作。为了正确测试Future的结果,您需要阻塞直到它完成。您可以使用Await并设置最长Duration等待。

import scala.concurrent._
import scala.concurrent.duration._

Await.result(testImage, Duration("10 seconds")) must not have length(0)

答案 4 :(得分:3)

想知道为什么@etorreborre没有提到“最终”

请参阅https://github.com/etorreborre/specs2/blob/master/tests/src/test/scala/org/specs2/matcher/EventuallyMatchersSpec.scala#L10-L43

class EventuallyMatchersSpec extends Specification with FutureMatchers with ExpectationsDescription { section("travis")
addParagraph { """
`eventually` can be used to retry any matcher until a maximum number of times is reached
or until it succeeds.
""" }

  "A matcher can match right away with eventually" in {
    1 must eventually(be_==(1))
  }
  "A matcher can match right away with eventually, even if negated" in {
    "1" must not (beNull.eventually)
  }
  "A matcher will be retried automatically until it matches" in {
    val iterator = List(1, 2, 3).iterator
    iterator.next must be_==(3).eventually
  }
  "A matcher can work with eventually and be_== but a type annotation is necessary or a be_=== matcher" in {
    val option: Option[Int] = Some(3)
    option must be_==(Some(3)).eventually
  }

答案 5 :(得分:0)

等待是一种反模式。永远不要使用它。 您可以使用ScalaFuturesIntegrationPatienceEventually之类的特征。

示例:

import org.specs2.mutable.Specification
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import scala.concurrent.Future

class AsyncWebClientSpec extends Specification with ScalaFutures
    with IntegrationPatience{

    "WebClient when downloading images" should {
        "for a valid link return non-zero content " in {
            whenReady(Future.successful("Done")){ testImage =>
                testImage must be equalTo "Done"           
                // Do whatever you need
            }

        }
    }
}