我正在尝试为特定方法编写单元测试,该方法使用给定的输入(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响应= client.execute(actualRequest)
我已经在我的项目中使用了specs2,所以如果有人知道如何使用specs2来实现这一目标,那就太好了。