当Scalatest测试喷雾服务,如何引入隐含价值?(When testing Spray serv

2019-10-22 18:51发布

我有一个服务:

trait MyService extends HttpService {

  def getDao(implicit dao: SomeDAO) = dao

  def someRoute = path("foo") {
    get {
      complete(getDao getSomething)
    }
  }
}

然后,我有一个演员:

class MyActor extends MyService with Actor {

  override def receive: Receive = runRoute(someRoute)

  def actorRefFactory: ActorRefFactory = context
}

我的测试类如下所示:

class MyServiceTest extends FlatSpec with ScalatestRouteTest with MyService with Matchers with MockFactory {

  override implicit def actorRefFactory: ActorSystem = system

  implicit val _dao: SomeDAO = mock[SomeDAO]

  "My service" should "return something" in {

    Get("/foo") ~> someRoute ~> check {
      status should be(OK)
    }
  }
}

但是,当我运行测试,编译器会抱怨,对于内含价值SomeDAO无法找到。 如何管理以获得SomeDAO进入我的服务? 我在想什么/我究竟做错了什么?

Answer 1:

我认为你最好声明implicitsomeRoute ,就像这样:

trait MyService extends HttpService {

def someRoute(implicit dao: SomeDAO) = path("foo") {
   get {
     complete(dao getSomething)
   }
 }
}

它应该编译,同时也更有意义,有一个方法只是为了获取一个隐含的。



Answer 2:

该ScalatestRouteTest已经提供了一种隐含ActorySystem。 从actorRefFactory方法删除“隐含的”修改和测试应该得到执行。

这解决了这个问题对我的代码



文章来源: When testing Spray services with Scalatest, how to introduce implicit values?