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

sharpest 阅读:71 2025-01-19 22:14:33 评论:0

我想用 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
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号