我有以下课程:
class Elem[T](t: T){
def doSome(f: T => Unit):Unit = f(t)
}
所以我想测试给定Elem
实例的函数调用(我在做mockito)。运行测试时
val f = mock(classOf[Int => Unit])
new Elem(1).doSome(f)
verify(f).apply(1)
我遇到以下异常:
Wanted but not invoked:
function1.apply$mcVI$sp(1);
However, there was exactly 1 interaction with this mock:
function1.apply(1);
这是合理的,因为Function1
专门用于Int
。所以进行测试
val f = mock(classOf[AnyRef => Unit])
new Elem(1.asInstanceOf[AnyRef]).doSome(f)
verify(f).apply(1.asInstanceOf[AnyRef])
工作正常。
有没有办法避免这种丑陋的演员阵容AnyRef
?也许有另一种工具比mockito更适合这种情况?
答案 0 :(得分:4)
这是强制编译器使用非专用泛型apply
:
def verifyGenericApply[X, Y](f: X => Y, x: X): Unit = {
verify(f).apply(x)
}
"Int function" should "invoke non-specialized apply" in {
class Elem[T](t: T){
def doSome(f: T => Unit):Unit = f(t)
}
val f = mock(classOf[Int => Unit])
new Elem(1).doSome(f)
verifyGenericApply(f, 1)
}
我对mockito
不够熟悉,不能保证这是惯用的,但是......
答案 1 :(得分:2)
ScalaMock似乎开箱即用:
import org.scalatest._
import org.scalatest.matchers._
import org.scalamock.scalatest.MockFactory
import org.scalamock.scalatest._
class Elem[T](t: T){
def doSome(f: T => Unit):Unit = f(t)
}
class ExampleSpec extends FlatSpec with Matchers with MockFactory {
"Elem.doSome" should "apply given function once" in {
val f = mockFunction[Int, Unit]
f.expects(1).returning({}).once
new Elem(1).doSome(f)
}
}
run(new ExampleSpec)