本文介绍了如何测试返回 Future 的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试一个返回 Future 的方法.我的尝试如下:
I'd like to test a method that returns a Future. My attempts were as follows:
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("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 的匹配器来测试期货.
Apart from the fact that I am unable to make this code work I guess that there could be a better way of testing a futures with a Future-oriented matcher.
如何在规范2中正确地做到这一点?
How to do it properly in specs2?
推荐答案您可以使用 Matcher.await 方法将 Matcher[T] 转换为 Matcher[Future[T]]:
You can use the Matcher.await method to transform a Matcher[T] into a Matcher[Future[T]]:
val testImage: Future[String] = AsyncWebClient.get("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更多推荐
如何测试返回 Future 的方法?
发布评论