如何模拟 Scala 单例对象? [英] How to mock a Scala singleton object?
问题描述
我正在尝试模拟 Scala 单例对象.特别是,我需要模拟在服务组件(被测类)中使用的对象 play.api.libs.ws.WS
.使用 Mockito 这是不可能的,测试执行失败的方式如下:
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)
阅读此处,Scalamock 似乎允许这样做:
Reading here, it seems that Scalamock allows to do it:
要模拟一个独立的单例对象,请使用org.scalamock.annotation.mockObject
.
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
}
}
}
我的 build.sbt 具有所有这些依赖项:
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",
[...]
但我找不到这个:org.scalamock.annotation.mockObject
可能这也可以使用 EasyMock 和 PowerMock 来完成,但我找不到任何 Scala 示例代码.
Probably this can be done also using EasyMock and PowerMock, but I cannot find any Scala example code.
有什么想法吗?
推荐答案
使用 ScalaMock 3 模拟单例对象不可能,但是 Paul Butcher 希望在 ScalaMock 4 中重新引入此功能(请参阅 http://paulbutcher.com/2014/04/15/scalamock-status-report/)
Mocking singleton objects using ScalaMock 3 is not possible, however Paul Butcher expects to reintroduce this feature in ScalaMock 4 (see http://paulbutcher.com/2014/04/15/scalamock-status-report/)
这篇关于如何模拟 Scala 单例对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!