【问题标题】:How to mock a call by name function using ScalaMock?如何使用 ScalaMock 模拟按名称调用的函数?
【发布时间】:2018-05-17 14:44:26
【问题描述】:

我希望能够使用 ScalaMock 模拟我的名称调用函数,以便它可以在我的模拟中运行传递的函数。

class MyTest extends Specification with MockFactory {

  trait myTrait {
    def myFunction[T](id: Int, name: String)(f: => T): Either[ErrorCode,T]
  }

  def futureFunction() = Future {
    sleep(Random.nextInt(500))
    10
  }

  "Mock my trait" should {
    "work" in {
      val test = mock[myTrait]

      (test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
        _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
      }
      test.myFunction(25)("test")(futureFunction()) must beEqualTo(10)
    }
  }

}

我试过这样模拟函数:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
    _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
  }

但是当我运行测试时,我得到了这个错误:

scala.concurrent.impl.Promise$DefaultPromise@69b28a51 cannot be cast to  Either

如何模拟它,让它在模拟中运行我的 futureFunction() 并返回结果。

【问题讨论】:

  • 您可以尝试使用returns(Either[ErrorCode, T])() 而不是onCall。嗯,我需要运行它来尝试解决它。​​

标签: scala unit-testing scalamock


【解决方案1】:

一位朋友帮我找到了解决方案。这个问题与我对 myFunction() 的模拟有关。我将一个按名称调用的函数传递给 myFunction()(f: => T),它在评估后返回 TmyFunction() 返回 Either[ErrorCode, T]。所以模拟应该是这样的:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall { test =>
    Right(test.productElement(2).asInstanceOf[() => T]())
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多