如何模拟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屋!