1

在下面的代码片段中,我需要确保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]()

4

1 回答 1

1

现在,我明白我犯的错误了;我试图将 curried 的名称调用参数Foo#foo转换为放置在其中的函数,在上面的示例中它是BinaryConverter#intToStr(x: Int): String.

相反,应该将参数转换为() => String然后调用,以便可以执行里面的代码。

(mockFoo.foo(_: Int)(_: String)).expects(2, *).onCall(_.productElement(1).asInstanceOf[() => String]())

于 2020-10-02T11:14:19.310 回答