在下面的代码片段中,我需要确保BinaryConverter#intToStr
调用它。
import org.scalamock.scalatest.MockFactory
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class Foo {
def foo(x: Int)(b: => String): String = b
}
class BinaryConverter {
def intToStr(x: Int): String = x.toBinaryString
}
class Converter(fooBar: Foo, converter: BinaryConverter) {
def convert2Bin(x: Int): String = fooBar.foo(x)(converter.intToStr(x))
}
class FooTest extends AnyFlatSpec with Matchers with MockFactory {
val mockFoo: Foo = mock[Foo]
val mockBinConverter: BinaryConverter = mock[BinaryConverter]
val converter = new Converter(mockFoo, mockBinConverter)
behavior of "Foo"
it should "mock foo doesn't work" in {
(mockBinConverter.intToStr _).expects(2).returns("Mock 10")
(mockFoo.foo(_: Int)(_: String)).expects(2, *).onCall(_.productElement(1).asInstanceOf[Int => String](2))
converter.convert2Bin(2) shouldBe "Mock 10"
}
}
我尝试使用 onCall 产品,但得到Converter$$Lambda$132/182531396 cannot be cast to scala.Function1
. 虽然,将无参数函数转换为 Function0 时,相同的代码仍然有效,.asInstanceOf[() => String]()