How to mock a call-by-name argument (like getOrElse) using ScalaMock?

流过昼夜 提交于 2019-12-01 03:47:26

The trick is to use Product version of onCall method, convert the second argument to () => String and call it:

class CallByNameMockSpec extends Specification with MockFactory {

  trait ToBeMocked {
    def getOrElse(arg: Int)(orElse: => String): String
  }

  "Mocking functions with call-by-name arguments" should {
    "work" in {
      val m = mock[ToBeMocked]

      (m.getOrElse (_: Int)(_: String)).expects(101, *).onCall(_.productElement(1).asInstanceOf[() => String]())

      m.getOrElse(101)("result") must beEqualTo("result")
    }
  }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!