如何在 Akka 演员中对 Dispatch Http 进行单元测试?

How to unit test Dispatch Http in an Akka actor?

我有一个Akka演员如下;它收到一条消息和 returns 一个 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 请求并 return 结果。此方法将在我的测试中被覆盖,如下所示:

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")}"
    }
  }

虽然有点简陋,但还是可以的。