在mockito中嘲笑泛型scala方法 [英] Mocking generic scala method in mockito
问题描述
我正在使用Mockito作为嘲讽框架开发一个Scala项目。我想模拟以下泛型Scala方法:
$ b $ pre $ def $ parseXml [T:ClassTag](xmlUrl:URL,xsdUrl:Option [ URL]):Option [T]
当我嘲笑我假设我可以使用像这样的Mockito匹配器:
when(xmlFileUnmarshallerMock.parseXml [org.mockito.Matchers.any [AddressBook]](org.mockito.Matchers.any [URL],org.mockito.Matchers.any [Option [URL]]))
.thenReturn(Some(defaultAddressBook))
但它不会编译,然后我尝试使用[Any]和[AddressBook],但两者都导致以下错误:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:使用参数匹配器无效!预计3个匹配者,2个记录。
问题在于您的 parseXml
函数实际上有三个参数,而不是两个,这就是 T:ClassTag
语法的简写:
pre $ def $ pa $ x [X]
当您试图嘲笑它时,scala会隐式提供第三个参数,但mockito不接受它,因为它不会接受它不允许在相同的存根通话中混合匹配器和非匹配。
底线是,您必须明确提供第三个参数,并将其设为匹配器:
when(parseXml [AddressBook](any,any)(any))
.thenReturn(Some(defaultAddressBook))
pre>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.
解决方案the problem is that your
parseXml
function actually takes three arguments, not two, that's what theT : 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))
这篇关于在mockito中嘲笑泛型scala方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!