首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SttpBackendStub进行单元测试流请求

使用SttpBackendStub进行单元测试流请求
EN

Stack Overflow用户
提问于 2020-04-28 01:57:17
回答 1查看 139关注 0票数 0

我有一个返回我想要测试的Source流的请求,如下所示:

代码语言:javascript
复制
/* class */
import sttp.client._

class HttpClient()
                (implicit sttpBackend: SttpBackend[Future, Source[ByteString, Any], Nothing]) {
  /** Start a download stream for large files */
  def downloadStream(url: String): Future[Response[Either[String, Source[ByteString, _]]]] = {
    request
      .get(uri"url")
      .response(asStream[Source[ByteString, Any]])
      .send()
  }
}
代码语言:javascript
复制
/* test */
import org.scalatest.FlatSpec
import org.scalatest.Matchers

class HttpClientSpec extends FlatSpec with Matchers {
  implicit val as = ActorSystem()
  implicit val mat = ActorMaterializer()
  implicit val ex = as

  "downloadStream" should "get a file stream from url" in {
    val url = s"http://example.com/api/v1/file/Test.txt"
    val body = "abcdefghijklmnopqrstuzwxyz"
    val expectedStream = Source.single[ByteString](body.getBytes)

    implicit val stubBackend = SttpBackendStub.asynchronousFuture
      .whenRequestMatches(req => req.method.method == "GET" && req.uri == uri"$url")
      .thenRespond(
        Response(Right(expectedStream), StatusCode.Ok)
      )

    val httpTest = new HttpClient()

    val response = Await.result(httpTest.downloadStream(url), 5.seconds)
    response.body.right.get should be(expectedStream)
  }
}

但它失败了,因为SttpBackendStub.asynchronousFuture does not handle stream responses

代码语言:javascript
复制
type mismatch;
[error]  found   : sttp.client.testing.SttpBackendStub[scala.concurrent.Future,Nothing]
[error]  required: sttp.client.SttpBackend[scala.concurrent.Future,akka.stream.scaladsl.Source[akka.util.ByteString,Any],Nothing]

我如何在不求助于scalamock的情况下使用SttpBackendStub

EN

回答 1

Stack Overflow用户

发布于 2020-04-28 01:57:17

只需创建您自己的存根类,它将extends预期的响应类型:

代码语言:javascript
复制
class StreamHttpStub
    extends SttpBackendStub[Future, Source[ByteString, Any]](new FutureMonad(), PartialFunction.empty, None) {
}

implicit val stubBackend = new StreamHttpStub()
  .whenRequestMatches(req => req.method.method == "GET" && req.uri == uri"$url")
  .thenRespond(
    Response(Right(expectedStream), StatusCode.Ok)
  )
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61465289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档