如何测试返回 Future 的方法?

编程入门 行业动态 更新时间:2024-10-10 20:17:56
本文介绍了如何测试返回 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 的方法?

本文发布于:2023-11-25 21:20:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   方法   Future

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!