【问题标题】:How to unit test Dispatch Http in an Akka actor?如何在 Akka 演员中对 Dispatch Http 进行单元测试?
【发布时间】:2015-05-15 21:43:11
【问题描述】:

我有一个 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()
    }
}

【问题讨论】:

    标签: scala unit-testing akka


    【解决方案1】:

    一种方法是对你的演员做这样的事情:

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

    这有点粗略,但很有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 2014-03-09
      • 2016-02-03
      • 1970-01-01
      相关资源
      最近更新 更多