我有一个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()
}
}
答案 0 :(得分:0)
一种方法是与你的演员做这样的事情:
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")}"
}
}
它有点粗糙,但可以有效。