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
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
}