0

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...

JohnBigs
  • 2,691
  • 3
  • 31
  • 61

1 Answers1

2
// 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!

Community
  • 1
  • 1
insan-e
  • 3,883
  • 3
  • 18
  • 43
  • thanks man! that helped. can you explain `import org.mockito.Matchers.{eq => eqMockito, _}` this import please? mainly `eq => eqMockito` – JohnBigs Apr 19 '17 at 08:31
  • @JohnBigs you're welcome! In Scala you can **rename** imported stuff, to avoid name conflicts. For example you want to refer to `java.util.List` as `JList` or something like that. Here we rename a method called `eq` to `eqMockito` (or whatever you want to call it). You can also exclude some stuff from importing, see http://stackoverflow.com/questions/27945005/import-symbols-with-wildcard-but-rename-or-ignore-some-of-them – insan-e Apr 19 '17 at 09:02
  • so we only changed the name so it wont clash with scala eq? – JohnBigs Apr 19 '17 at 09:56
  • 1
    Yes, that's the only reason. Feel free to experiment without it. – insan-e Apr 19 '17 at 10:00