【发布时间】:2017-05-11 06:51:35
【问题描述】:
鉴于以下使用 Mockito 模拟 Scala 类的代码,我收到错误并且无法编译:
import org.mockito.Mockito._
class Testeable {
def fun1 = 1
def fun2 = 2
}
object test {
def getMock = {
val testMock = mock[Testeable] // <-- this line throws the error
when(testMock.fun1).thenReturn(3)
testMock
}
}
错误是:
对重载定义的模糊引用,两个方法都在模拟 类型的对象 Mockito (x$1: Class[common.Testeable], x$2: org.mockito.MockSettings)common.Testeable 和对象中的方法模拟 Mockito 类型 (x$1: Class[common.Testeable], x$2: org.mockito.stubbing.Answer[_])common.Testeable 匹配预期类型?
我只是嘲笑了一个类,有什么歧义?
【问题讨论】:
-
mock(classOf[Testeable])?它需要一个java.lang.Class,而classOf方法提供它,就像在Java 中你可以做Testeable.class。 -
更正,
Any类有一个getClass方法,因此对于非泛型类,如Int、String等,您可以使用getClass和泛型类,如List[T]你使用classOf[List[_]]来自Predef... -
谢谢,它使用
mock(classOf[Testeable])工作 -
@insan-e 模拟
Int听起来是个好主意! :)