scala - 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 来实现这一点,那就太好了。
解决方案
推荐阅读
- c# - 如何回到列表的开头?
- c# - 保持控制台打开而不中断其他功能
- python - 我无法检索全局变量中的文本
- csv - Azure Databricks,无法使用嵌套列表读取逗号分隔的 CSV 文件
- github - Spring Cloud / Jgit / Github 使用 SSH 失败
- javascript - 处理完所有图块后运行函数
- java - 如何在 Netbeans 的控制台中打印希伯来语字符
- pandas - Python Pandas df.mean() 输出未对日期进行排序
- excel - 在 VBA Excel 中,根据特定条件从用户窗体传递值的代码
- c++ - 为什么 cin.get() 卡在换行符上?