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

前端 未结 1 1530
迷失自我
迷失自我 2021-01-11 21:39

I\'d like to be able to mock a return value of getOrElse method so that it returns what is passed as orElse call-by-name argument with ScalaMock

1条回答
  •  广开言路
    2021-01-11 22:09

    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")
        }
      }
    
    }
    

    0 讨论(0)
提交回复
热议问题