[英]How to unit test Dispatch Http in an Akka actor?
I have a Akka actor as follows; 我有一个Akka演员,如下所示; it receives a message and returns a HTTP response. 它收到一条消息并返回HTTP响应。
I am having trouble testing the interaction with Dispatch Http, it is a nice library but seems difficult to test. 我在测试与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()
}
}
One way would be to do something like this with your actor: 一种方法是与演员一起执行以下操作:
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(",")}"
}
Here, I'm providing a method, executeRequest
that all it does it execute the http request and return the result. 在这里,我提供了一个方法executeRequest
,它执行的所有操作都会执行http请求并返回结果。 This method will be overridden in my test like so: 此方法将在我的测试中被覆盖,如下所示:
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")}"
}
}
It's a bit crude but can be effective. 这有点粗糙,但可以有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.