scala - 如何不使用 ScalatestRouteTest 绑定(bind)到本地主机

标签 scala akka akka-testkit

我想用 ScalatestRouteTest 测试路由,如下所示:

trait MyRoutes extends Directives {

  self: Api with ExecutionContextProvider =>

  val myRoutes: Route =
    pathPrefix("api") {
      path("") {
        (get & entity(as[MyState])) {
          request => {
            complete(doSomething(request.operation))
          }
        }
      }
    }
  }
}


class RoutesSpec extends WordSpecLike with Api with ScalatestRouteTest 
  with Matchers with MyRoutes with MockitoSugar {

  "The Routes" should {

    "return status code success" in {
      Get() ~> myRoutes ~> check {
        status shouldEqual StatusCodes.Success
      }
    }
  }
}

运行测试时出现运行时错误:

Could not run test MyRoutesSpec: org.jboss.netty.channel.ChannelException: Failed to bind to: /127.0.0.1:2552

我不想绑定(bind)到本地主机。如何实现?

最佳答案

解决方案是禁用远程处理和集群(这是在单独的配置文件中启用的)并使用默认提供程序。

actor remoting 和 clustering 与正在运行的应用程序冲突(为路由测试启动)。它们采用相同的配置,因此都尝试使用相同的端口,但会发生冲突。

在 trait MyRoutes 中添加了以下代码以使其工作:

// Quick hack: use a lazy val so that actor system can "instantiate" it
// in the overridden method in ScalatestRouteTest while the constructor 
// of this class has not yet been called.
lazy val routeTestConfig =
  """
    | akka.actor.provider = "akka.actor.LocalActorRefProvider"
    | persistence.journal.plugin = "akka.persistence.journal.inmem"
  """.stripMargin

override def createActorSystem(): ActorSystem = 
  ActorSystem("RouteTest", ConfigFactory.parseString(routeTestConfig))

关于scala - 如何不使用 ScalatestRouteTest 绑定(bind)到本地主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36062290/

相关文章:

amazon-web-services - 在 EB 上的 Docker 中运行的应用程序拒绝连接到自己

scala - 无法解析符号 "TestKit"

multithreading - 如何在 future 中包装 Web Worker 响应消息?

java - 用于监视 Akka 独立应用程序的 GUI?

json - 如何使用 json 模式验证器验证可为空类型?

java - 如何保证一段代码在多线程环境下只执行一次?

scala - TestActorRef : Could not get the underlyingActor, 什么也没说

java - 如何模拟基于 ActorSelection 的 Actor ?

java - 对象 TemplatesPlugin 不是包 securesocial.controllers 的成员

json - 如何在 Play Framework 中的 Json 读取中添加自定义验证错误