我正在尝试模拟Scala单例对象。特别是,我需要模拟服务组件(被测类)中使用的对象play.api.libs.ws.WS
。
使用Mockito是不可能的,测试执行将通过以下方式失败:
[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)
阅读here,似乎Scalamock允许这样做:
我的服务组件是这样的:
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
}
}
}
我的build.sbt具有所有这些依赖项:
[...]
"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",
[...]
但我找不到这个:
org.scalamock.annotation.mockObject
可能也可以使用EasyMock和PowerMock完成此操作,但是我找不到任何Scala示例代码。
任何想法?
最佳答案
使用ScalaMock 3模拟单例对象是,不是,但是Paul Butcher希望在ScalaMock 4中重新引入此功能(请参阅http://paulbutcher.com/2014/04/15/scalamock-status-report/)