How to mock a Scala singleton object?

后端 未结 4 419
我在风中等你
我在风中等你 2020-12-09 03:53

I am trying to mock a Scala singleton object. In particular, I need to mock the object play.api.libs.ws.WS used inside a service component (class under test). U

4条回答
  •  情歌与酒
    2020-12-09 04:44

    Don't mock the singleton. Instead of WS, make your service component depend on a thin facade hiding it:

    trait GeolocationService {
      def ws: (String, Seq[String]) => Promise[Response] = { (url, params) =>
        wsClient.url(serviceProviderEndpoint.get).withQueryString(params: _*).get()
      }
      def getPath(origin: Location, destination: Location): Future[Route]
    }
    

    and in your test, just override ws method with a mock, which is now easy to create:

    val mockedWs = mock[(String, Seq[String]) => Promise[Response]]
    // TODO specify mock's behavior here
    val service = new DefaultGeolocationService() {
      override def ws = mockedWs
    }
    

提交回复
热议问题