首页 > 解决方案 > scala specs2模拟http客户端响应

问题描述

我正在尝试为特定方法编写单元测试,该方法调用具有给定输入(url、http 方法、正文、标头)的 REST 端点。下面是代码。

  def genericAPICall(uri: String, method: String, headers: Map[String, String], body: HttpEntity): APIResponse = {
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.util.EntityUtils
import java.nio.charset.StandardCharsets

val client = HttpClientBuilder.create.build
val request = method match {
  case "GET" => Some(new HttpGet(uri))
  case "POST" => {
    val post =  new HttpPost(uri)
    post.setEntity(body)
    Some(post)
  }
  case "PUT" => {
    val put =  new HttpPut(uri)
    put.setEntity(body)
    Some(put)
  }
  case "DELETE" => Some(new HttpDelete(uri))
  case _ =>  None
}

if (request.isDefined) {
  val actualRequest = request.get

  if (headers.nonEmpty) {
    for ((headerName,headerVal) <- headers) {
      actualRequest.addHeader(headerName,headerVal)
    }
  } else {
    actualRequest.addHeader("Accept", "application/json")
    actualRequest.addHeader("Content-Type", "application/json")
  }


  val response: CloseableHttpResponse = null
  try {

    val response = client.execute(actualRequest)

    val entity = response.getEntity
    // use org.apache.http.util.EntityUtils to read json as string
    val str = EntityUtils.toString(entity, StandardCharsets.UTF_8)
    APIResponse(response.getStatusLine.getStatusCode(), str, null)
  } catch {
    case e: Exception => APIResponse(500, null, e)
  }finally {
    if (response != null)
      response.close()
  }
} else {
  APIResponse(500, null, new Exception("not a valid http method"))
}}

无论如何我可以在 client.execute 下面模拟吗?所以我可以避免实际调用我的测试网址?

val response = client.execute(actualRequest)

我已经在我的项目中使用了 specs2,所以如果有人知道如何使用 specs2 来实现这一点,那就太好了。

标签: scalamockingsbtmockitospecs2

解决方案


推荐阅读