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).
Using Mockito this is not possible, the test execution fails in the following way:
[error] MockitoException: :
[error] Cannot mock/spy class play.api.libs.ws.WS$
[error] Mockito cannot mock/spy following:
[error] - final classes
[error] - anonymous classes
[error] - primitive types (GeolocationSpec.scala:18)
Reading here, it seems that Scalamock allows to do it:
To mock a standalone singleton object, use
org.scalamock.annotation.mockObject
.
My service component is something like this:
trait GeolocationService {
def wsClient = WS
def getPath(origin: Location, destination: Location): Future[Route]
}
class DefaultGeolocationService extends GeolocationService {
val serviceProviderEndpoint = Play.current.configuration.getString("api.directions.endpoint")
override def getPath(origin: Location, destination: Location): Future[Route] = {
val params = Seq(
"origin" -> s"${origin.lat},${origin.lon}",
"destination" -> s"${destination.lat},${destination.lon}"
);
val resp = wsClient.url(serviceProviderEndpoint.get).withQueryString(params: _*).get()
resp.map {
// omitted code
}
}
}
My build.sbt has all these dependencies:
[...]
"org.scalatest" %% "scalatest" % "2.2.1",
"org.specs2" %% "specs2" % "2.3.13" % "test",
"org.scalamock" %% "scalamock-specs2-support" % "3.0.1" % "test",
"org.scalamock" %% "scalamock-scalatest-support" % "3.0.1" % "test",
"org.scalamock" %% "scalamock" % "3.0.1",
[...]
but I cannot find this: org.scalamock.annotation.mockObject
Probably this can be done also using EasyMock and PowerMock, but I cannot find any Scala example code.
Any idea?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…