How to mock a Scala singleton object?

≯℡__Kan透↙ 提交于 2020-01-20 02:16:49

问题


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?


回答1:


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/)




回答2:


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
}



回答3:


I don't like to change the design to accommodate this kind of limitation. basically what I can get is all to change the design and then use the mock framework

  //since mocking frameworks on SCALA is not support mocking singleton
  //hacks are either required to change the design or ...
  //I'd rather putting the mocking logic here by myself
  var testUser:Option[User] = None;

  def getCurrentUser(request: Request[Object]) = {
    if( testUser != None ){
    testUser;
  }

hope it helps.




回答4:


Why you don't use the cake pattern?

It's a little verbose but it will solve your mocking problem.

trait GeolocationServiceComponent {
   val geolocationService:GeolocationService
   trait GeolocationService {      
      def wsClient
      def getPath(origin:Location, destination: Location): Future[Route]   
   }
}

trait GeolocationServiceComponentImpl {
   val geolocationService = new GeolocationService {
      override def wsClient = WS
   }
}


class DefaultGeolocationService extends GeolocationServiceComponent ...

//Defined into your test class
trait MockGeolocationServiceComponent {
       val geolocationService = Mock[GeolocationService]
//Here you define your mock logic       
}

You can also use monads to do this, but I have never implemented, it's described here: Scala dependency injection: alternatives to implicit parameters



来源:https://stackoverflow.com/questions/25293758/how-to-mock-a-scala-singleton-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!