Yuqing Peng Yuqing Peng - 3 years ago 88
Scala Question

mocking generic method using Mockito and Scala

I'm trying to write a test for the following function in Finatra HttpClient.

def executeJson[T: Manifest](
request: Request,
expectedStatus: Status = Status.Ok): Future[T] = {...}


According to another question answered on StackOverflow. mocking generic scala method in mockito. This is a shorthand for:

def executeJson[T](
request: Request,
expectedStatus: Status = Status.Ok)
(implicit T: Manifest[T]): Futuren[T] = {...}


So I tried,

verify(httpClientMock, times(1)).executeJson[JiraProject]
(argThat(new RequestMatcher(req)))(Matchers.any())


Unfortunately, it didn't solve my problem. I still got the following error.

Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at org.specs.mock.MockitoStubs$class.argThat(Mockito.scala:331)

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));


I also tried
Matchers.eq(Manifest[JiraProject])
, it complains that
value Manifest of type scala.reflect.ManifestFactory.type does not take type parameters
.

I'm new to Scala and Mockito, is there anything I did wrong or I misunderstood?

Thanks in advance for any help!

Found out the problem! So the executeJson actually takes 3 params- request, expectedStatus, and a Manifest. However, because expectedStatus is an optional, I didn't explicit pass it, that's why it complained. So, the final code should be
verify(httpClientMock, times(1)).executeJson[JiraProject](argThat(new RequestMatcher(req)), Matchers.any[Status])(Matchers.any())

Answer Source

Your problem is that you're using equality in the first parameter and matcher for the second one. Try using matchers for all arguments.

But a bigger problem that I feel here is that you're trying to mock 3rd party library - this is something you should avoid. This would also solve your problem. Here's some extra read about it - enter link description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download