【问题标题】:Mocking generic scala method in mockito在 mockito 中模拟通用 scala 方法
【发布时间】:2016-12-25 02:56:44
【问题描述】:

我正在开发一个使用 Mockito 作为模拟框架的 Scala 项目。我想模拟以下通用 Scala 方法:

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:  Invalid use of argument matchers! 3 matchers expected, 2 recorded.

【问题讨论】:

    标签: scala unit-testing generics mockito


    【解决方案1】:

    问题在于您的 parseXml 函数实际上需要三个参数,而不是两个,这就是 T : ClassTag 语法的简写:

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

    当您尝试模拟它时,scala 隐式提供第三个参数,但 mockito 不接受它,因为它不允许在同一个存根调用中混合匹配器和非匹配器。

    底线是,您必须明确提供第三个参数,并使其成为匹配器:

    when(parseXml[AddressBook](any, any)(any))
      .thenReturn(Some(defaultAddressBook))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 2023-03-20
      相关资源
      最近更新 更多