Search code examples
scalamockingmockitoscalatest

Mocking a dynamic class method argument using scalatest/mockiton


this is how im mocking my service call and returning a fake result:

when(myService.doSomething("",fakeRequestAsModel)) thenReturn fakeResult

val result = call(controller.myActionMethod(), request)

the problem is in the controller method myActionMethod when I call doSomething and passing the arguments im calling some property that that will only return something in production...

def myActionMethod() ... = {

   myService.doSomething(request.getSomeValue,requestAsModel)
   ...
}

so, getSomeValue is a method i can call only in production, it comes with a 3rd party library and I cant override it.

How can I still mock this call so request.getSomeValue wont throw me an exception?

and request.getSomeValue is dynamic, I cant unfortunately put it in configuration...


Solution

  • // we rename this because Scala defines `eq` on `AnyRef`
    import org.mockito.Matchers.{eq => eqMockito, _} 
    ...
    when(myService.doSomething(anyString(), eqMockito(fakeRequestAsModel))) 
      thenReturn fakeResult
    

    Here we want Mockito to return this answer when any string is sent and exact fakeRequestAsModel, which is what you want.


    Notes:

    1. Be careful not to mix any matchers with normal values, you cant say: when(myService.doSomething(anyString(), fakeRequestAsModel)).
      You need to wrap normal value with eqMockito() method.
    2. You can use any[classOf[T]] for type-parametrized arguments.
    3. Be extra careful with implicits.

    Hope it helps!