[英]How to unit test Dispatch Http in an Akka actor?
我有一個Akka演員,如下所示; 它收到一條消息並返回HTTP響應。
我在測試與Dispatch Http的交互時遇到麻煩,這是一個不錯的庫,但似乎很難測試。
class Service(serviceUrl:String) extends Actor with ActorLogging {
implicit val ec = context .dispatcher
override def receive: Receive = {
case Get(ids) => request(ids)
}
private def request(ids:Seq[Int]):Unit = {
val requestUrl = buildRequestUrl(ids)
val request = url(requestUrl).GET
Http(request) pipeTo sender()
}
}
一種方法是與演員一起執行以下操作:
case class Get(ids:Seq[Int])
class Service(serviceUrl:String) extends Actor with ActorLogging {
implicit val ec = context .dispatcher
def receive: Receive = {
case Get(ids) => request(ids)
}
def request(ids:Seq[Int]):Unit = {
val requestUrl = buildRequestUrl(ids)
val request = url(requestUrl).GET
executeRequest(request) pipeTo sender()
}
def executeRequest(req:Req) = Http(req)
def buildRequestUrl(ids:Seq[Int]):String = s"http://someurl.com/?ids=${ids.mkString(",")}"
}
在這里,我提供了一個方法executeRequest
,它執行的所有操作都會執行http請求並返回結果。 此方法將在我的測試中被覆蓋,如下所示:
class ServiceTest extends TestKit(ActorSystem("test")) with SpecificationLike with Mockito with ImplicitSender{
trait scoping extends Scope{
def mockResult:Response
var url:String = ""
val testRef = TestActorRef(new Service(""){
override def executeRequest(req:Req) = {
url = req.toRequest.getUrl()
Future.successful(mockResult)
}
})
}
"A request to service " should{
"execute the request and return the response" in new scoping{
val mockedResp = mock[Response]
def mockResult = mockedResp
testRef ! Get(Seq(1,2,3))
expectMsg(mockedResp)
url ==== s"http://someurl.com/?ids=${URLEncoder.encode("1,2,3")}"
}
}
這有點粗糙,但可以有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.