【问题标题】:Scalamock: Mocking call by-name function with argumentsScalamock:使用参数模拟按名称调用函数
【发布时间】:2020-10-01 08:53:57
【问题描述】:

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

【问题讨论】:

    标签: unit-testing mocking higher-order-functions scalamock callbyname


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2021-09-21
      相关资源
      最近更新 更多