如何使用spraytestkit和HttpServiceActor进行scalatest工作

Jas*_*Jas 5 scala akka spray

我查看了sp1 1.3.1 testkit文档,但找不到下面我需要的正确示例:我有这个示例spray 1.3.1服务

trait MyService extends HttpServiceActor {
  def receive = runRoute(routes)

  val isAliveRoute = path("isalive") {
    get {
        complete("YES")
    }
  }
  val routes = isAliveRoute
}
Run Code Online (Sandbox Code Playgroud)

我正试图测试它,spray test-kit但没有这样做,这是我的TestCase

@RunWith(classOf[JUnitRunner])
class MyServiceTest extends FlatSpec with ScalatestRouteTest with ShouldMatchers with MyService {
  "The service" should "return a greeting for GET requests to the isalive" in {
    Get() ~> isAliveRoute ~> check {
      responseAs[String] should be("YES")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了

错误:(15,87)非法继承; superclass FlatSpec不是mixin trait的超类HttpServiceActor的子类MyService类MyServiceTest使用ScalatestRouteTest扩展FlatSpec,使用带MyService的ShouldMatchers {^
^

和:

错误:(17,11)找不到参数ta的隐含值:MyServiceTest.this.TildeArrow [spray.routing.RequestContext,Unit] Get()〜> isAliveRoute~> check {^

有办法解决这个问题吗?我可以使用我的服务extend HttpServiceActor并仍然可以使用scalatest和spray testkit进行测试吗?如果是这样的话?我想继续扩展HttpServiceActor使生活更轻松,代码更紧凑和可读.但我也想用scalatest进行测试.

所以我尝试更新代码,因为评论说要拆分为特征和服务,如:https: //github.com/spray/spray-template/blob/on_spray-can_1.1/src/main/scala/com/example/ MyService.scala

class MyServiceActor extends Actor with MyService {
  def actorRefFactory = context
  def receive = runRoute(routes)
}

trait MyService extends HttpService {

  val isAliveRoute = path("isalive") {
    get {
        complete("OK")
    }
  }
  val routes = isAliveRoute
}




@RunWith(classOf[JUnitRunner])
class MyServiceTest extends FlatSpec with ShouldMatchers with MyService with ScalatestRouteTest {
  def actorRefFactory = system

  "The service" should "return a greeting for GET requests to the isalive" in {
    Get() ~> isAliveRoute ~> check {
      responseAs[String] should be("YES")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我得到:

测试从13:26开始... [DEBUG] [2014年4月14日13:26:25.813] [ScalaTest-run] [EventStream(akka:// com-server-web-conf-MyServiceTest)] logger log1-记录$ DefaultLogger已启动[DEBUG] [05/14/2014 13:26:25.814] [ScalaTest-run] [EventStream(akka:// com-server-web-conf-MyServiceTest)]默认记录器已启动请求未处理org .scalatest.exceptions.TestFailedException:请求未在spray.testkit.ScalatestInterface $ class.failTest(ScalatestInterface.scala:25)处理

Wal*_*ski 2

我也遇到过类似的问题,但有一点不同。在完整的声明中,我已向另一个参与者发送消息,因此我需要参与者功能来测试行为。我是这样解决的:

trait MyService extends HttpService {
 val myActor: ActorRef
 val homeS: ActorRef 
 (...)
Run Code Online (Sandbox Code Playgroud)

并在 get 内发送消息

path("isalive") { get {
ctx: RequestContext => homeS.tell(ctx, myActor ) }
//on homeS actor:
def receive = {
case ctx: RequestContext =>
  ctx.complete( ... )
Run Code Online (Sandbox Code Playgroud)

但如果您不需要 MyService 中的 actor 功能,那么更好的做法是像@jrudolph 在评论中所说的那样。

完整代码在这里: https: //github.com/kastoestoramadus/simple_zookeeper.git