Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking generic scala method in mockito

I'm working on a Scala project using Mockito as mocking framework. I wanted to mock the following generic Scala method:

def parseXml[T: ClassTag](xmlUrl: URL, xsdUrl: Option[URL]): Option[T] 

When mocking i assumed i could use on of Mockito's matchers like so:

when(xmlFileUnmarshallerMock.parseXml[org.mockito.Matchers.any[AddressBook]](org.mockito.Matchers.any[URL], org.mockito.Matchers.any[Option[URL]]))
    .thenReturn(Some(defaultAddressBook))

But it won't compile, then i tried both using [Any] and [AddressBook], but both results in the following error:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:  Invalid use of argument matchers! 3 matchers expected, 2 recorded.
like image 813
JonasMH Avatar asked Aug 18 '16 08:08

JonasMH


1 Answers

the problem is that your parseXml function actually takes three arguments, not two, that's what the T : ClassTag syntax is shorthand for:

def parseXml[T](xmlUrl: URL, xsdUrl: Option[URL])(implicit classTag: ClassTag[T]): Option[T] 

When you are trying to mock it, scala implicitly supplies the third parameter, but mockito does not accept it, because it doesn't allow mixing matchers and non-matches in the same stubbing call.

The bottom line is, that you have to provide the third parameter explicitly, and make it a matcher:

when(parseXml[AddressBook](any, any)(any))
  .thenReturn(Some(defaultAddressBook))
like image 91
Dima Avatar answered Sep 21 '22 23:09

Dima